Given an array of integers, find the subarray with smallest sum.
Return the sum of the subarray.
Notice
The subarray should contain one integer at least.
Example
解题思路:
For [1, -1, -2, 1]
, return -3
.
1、贪心算法的应用。如果已求的当前和temp大于0,先与当前最小值比较出结果,然后将temp置0,继续下一轮。
class Solution {
public:
/*
* @param nums: a list of integers
* @return: A integer indicate the sum of minimum subarray
*/
int minSubArray(vector<int> &nums)
{
// write your code here
if(nums.size() <= 0)
return 0;
int min = nums[0];
int temp = 0;
for(int i=0;i<nums.size();i++)
{
temp += nums[i];
min = min > temp ? temp : min;
if(temp>0)
temp = 0;
}
return min;
}
};