Maximum Subarray

Given an integer arraynums, 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.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution

First attempt solution, but it is dead end because of time complexity.

class Solution {
    public int maxSubArray(int[] nums) {
        // 1.
        // [1, -2] -> 0, 0 -> 1 > -... yes, max = 1, move end++, 0, 1 -> -1 > 1 no, so 1
        // [-2, 1, -3-, 4], 0, 0 -> -2, 0, 1 -> -1 - start++, 1, 1 -> 1 yes, end++
        // two pointers, start = 0; end = 0
        // max sum = Integer.MIN_VALUE
        // current sum = sum(nums, start, end)
        // if (current > max) max = current
        // else, increment end
        int start = 0;
        int end = 0;
        int max = Integer.MIN_VALUE;

        while(start < nums.length && end < nums.length) {
           int sum = sum(nums, start, end);
           if (sum > max) {
               max = sum;
           } else {
               start++;
           }
            end++;
        }
        return max;
    }

    public int sum(int[] nums, int start, int end) {
        int sum = nums[start];
        int i = start + 1;
        while (i <= end) {
            sum += nums[i];
            i++;
        }
        return sum;
    }
}

Other solution.

Here is a solution using dynamic programming. It is not faster, but it is interesting as well.

Here is the sample input and output.

Last updated

Was this helpful?