lintcode-easy-Minimum Subarray

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

Return the sum of the subarray.

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

 

这道题就是把Maximum Subarray反过来写一下

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: A integer indicate the sum of minimum subarray
     */
    public int minSubArray(ArrayList<Integer> nums) {
        // write your code
        if(nums == null || nums.size() == 0)
            return 0;
        
        int result = nums.get(0);
        int sum = nums.get(0);
        
        for(int i = 1; i < nums.size(); i++){
            if(sum > 0)
                sum = 0;
            sum += nums.get(i);
            
            if(result > sum)
                result = sum;
        }
        
        return result;
    }
}

 

你可能感兴趣的:(lintcode-easy-Minimum Subarray)