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
.
Analyse: Greedy. If the previous sum is larger than 0, then we shouldn‘t combine the current value with the previous sum. Otherwise, we should combine them together. Every time we deal with a value, we should update the minSum.
Runtime: 36ms
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 10 // greedy 11 if (nums.empty()) return 0; 12 13 int minSum = INT_MAX, tempSum = 0; 14 for (int i = 0; i < nums.size(); i++) { 15 if (tempSum > 0) 16 tempSum = nums[i]; 17 else 18 tempSum += nums[i]; 19 20 minSum = min(minSum, tempSum); 21 } 22 return minSum; 23 } 24 };
时间: 2024-10-10 16:43:00