题目来源:http://www.lintcode.com/zh-cn/problem/minimum-subarray/
解法同最大子数组:
令currSum为当前最小子数组的和,minSum为最后要返回的最小子数组的和。a[j]有两种选择,要么放入前面的子数组,要么作为新子数组的第一个元素。如果currSum加上当前元素a[j]后不大于a[j],则令currSum再加上a[j]。否则currSum重新赋值为a[j]。同时,当currSum < minSum,则更新minSum = currSum,否则保持原值。即
currSum = min(a[j], currSum + a[j]
minSum = min(maxSum, currSum)
可以accept的程序如下:
1 class Solution { 2 public: 3 /** 4 * @param nums: a list of integers 5 * @return: A integer denote the sum of minimum subarray 6 */ 7 int minSubArray(vector<int> nums) { 8 // write your code here 9 int currSum = 0; 10 int minSum = nums[0]; 11 for (int j = 0; j < nums.size(); j++) 12 { 13 currSum = min(nums[j],currSum + nums[j]); 14 minSum = min(minSum,currSum); 15 } 16 return minSum; 17 } 18 };