首页 > 代码库 > Minimum Subarray
Minimum Subarray
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 // greedy11 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 };
Minimum Subarray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。