Lintcode: Minimum Subarray

C++

Divide-Conquer[71% passed]

复制代码
 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 n = nums.size();
10         if (n == 1) {
11             return nums[0];
12         }
13         int *arr = nums.data();
14         return helper(arr, n);
15     }
16     int helper(int *arr, int n) {
17         // terminate
18         if ( n == 1 ) {
19             return arr[0];
20         }
21         // divide
22         int mid = n>>1;
23         int ans = min(helper(arr, mid), helper(arr + mid, n - mid));
24         // conquer
25         int now = arr[mid - 1], may = now;
26         for (int i = mid-2; i >= 0; --i) {
27             may = min(may, now += arr[i]);
28         }
29         now = may;
30         for (int i = mid; i <= n; ++i) {
31             may = min(may, now += arr[i]);
32         }
33         // return
34         return min(may, ans);
35     }
36 };
复制代码

C++, dp

复制代码
 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 n = nums.size();
10         if (n == 1) {
11             return nums[0];
12         }
13         vector<int> dp(n);
14         dp[0] = nums[0];
15         int ans = nums[0];
16         for (int i = 1; i < n ; ++i) {
17             dp[i] = min(nums[i], dp[i - 1]+nums[i]);
18             ans = min(dp[i], ans);
19         }
20         return ans;
21     }
22 };
复制代码

C++,dp,O(1) space

复制代码
 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 n = nums.size();
10         if (n == 1) {
11             return nums[0];
12         }
13         int endHere = nums[0];
14         int ans = nums[0];
15         for (int i = 1; i < n ; ++i) {
16             endHere = min(nums[i], endHere+nums[i]);
17             ans = min(endHere, ans);
18         }
19         return ans;
20     }
21 };
复制代码

 


本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5006769.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值