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

Minimum Subarray

时间:2016-09-12 14:02:29      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

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.

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 };

 

Minimum Subarray

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5864384.html

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