码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode] Minimum Subarray

时间:2015-11-26 06:55:47      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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

Note

The subarray should contain at least one integer.

 

////If sum is greater than 0, it is not useful for the rest of numbers, so , get rid of it , set it as 0

////keep summing up the next one , if it is less than 0, keep it, keep summing next number.

 

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
        int sum=nums.get(0);
        int minSum=nums.get(0);
        for(int i=1;i<nums.size();i++)
        {
            if(sum>0) sum=0;
            sum=sum+nums.get(i);
            minSum=Math.min(minSum,sum);
        }
        return minSum;
    }
}

 

[lintcode] Minimum Subarray

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/4996502.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!