Minimum Subarray

Minimum Subarray

Given an array of integers, find the subarray with smallest sum.

Return the sum of the subarray.

Example

For [1, -1, -2, 1], return -3

Note

The subarray should contain at least one integer.

Solution: O(n) time O(1) space. one pass. Prefix Sum

 

public int minSubArray(ArrayList<Integer> nums) {
    if (nums == null || nums.size() == 0) {
        return 0;
    }
    int minSum = Integer.MAX_VALUE;
    int sum = 0;
    int maxSum = 0;
    for (Integer num : nums) {
        sum += num;
        minSum = Math.min(minSum, sum - maxSum);
        maxSum = Math.max(maxSum, sum);
    }
    return minSum;
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *