L53 Maximum Subarray

greedy

Problem

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

Solution

greedy: Tc O(n), SC O(1)

Create two int value, cur and max. cur is to store the current max sum, to do this, if cur greater than 0, the plus the next value. if not , just equal to next value; max is to store the max sum seen so far. then max is the result

public int subArray(int[] nums){
    if(nums == null || nums.length == 0) return 0;
    int cur = nums[0];
    int max = cur;
    for(int i = 1; i < nums.length; i++){
        if(cur > 0) cur += nums[i];
        else cur = nums[i];
        max = Math.max(cur, max);
    }
    return max;
    
}

Last updated

Was this helpful?