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

[LeetCode] Maximum Subarray Sum

时间:2015-08-16 16:22:54      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:


Dynamic Programming

There is a nice introduction to the DP algorithm in this Wikipedia article. The idea is to maintain a running maximum smax and a current summation sum. When we visit each num in nums, addnum to sum, then update smax if necessary or reset sum to 0 if it becomes negative.

The code is as follows.

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int sum = 0, smax = INT_MIN;
 5         for (int num : nums) {
 6             sum += num;
 7             if (sum > smax) smax = sum;
 8             if (sum < 0) sum = 0;
 9         }
10         return smax;
11     }
12 };

Divide and Conquer

The DC algorithm breaks nums into two halves and find the maximum subarray sum in them recursively. Well, the most tricky part is to handle the case that the maximum subarray may span the two halves. For this case, we use a linear algorithm: starting from the middle element and move to both ends (left and right ends), record the maximum sum we have seen. In this case, the maximum sum is finally equal to the middle element plus the maximum sum of moving leftwards and the maximum sum of moving rightwards.

Well, the code is just a translation of the above idea.

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int smax = INT_MIN, n = nums.size();
 5         return maxSub(nums, 0, n - 1, smax);
 6     }
 7 private:
 8     int maxSub(vector<int>& nums, int l, int r, int smax) {
 9         if (l > r) return INT_MIN;
10         int m = l + ((r - l) >> 1);
11         int lm = maxSub(nums, l, m - 1, smax); // left half
12         int rm = maxSub(nums, m + 1, r, smax); // right half
13         int i, sum, ml = 0, mr = 0;
14         // Move leftwards
15         for (i = m - 1, sum = 0; i >= l; i--) {
16             sum += nums[i];
17             ml = max(sum, ml); 
18         }
19         // Move rightwards
20         for (i = m + 1, sum = 0; i <= r; i++) {
21             sum += nums[i];
22             mr = max(sum, mr);
23         }
24         return max(smax, max(ml + mr + nums[m], max(lm, rm)));
25     }
26 };

 

[LeetCode] Maximum Subarray Sum

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4734493.html

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