[LeetCode] Maximum Subarray Sum
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.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = , smax = INT_MIN;
for (int num : nums) {
sum += num;
if (sum > smax) smax = sum;
if (sum < ) sum = ;
}
return smax;
}
};
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.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int smax = INT_MIN, n = nums.size();
return maxSub(nums, , n - , smax);
}
private:
int maxSub(vector<int>& nums, int l, int r, int smax) {
if (l > r) return INT_MIN;
int m = l + ((r - l) >> );
int lm = maxSub(nums, l, m - , smax); // left half
int rm = maxSub(nums, m + , r, smax); // right half
int i, sum, ml = , mr = ;
// Move leftwards
for (i = m - , sum = ; i >= l; i--) {
sum += nums[i];
ml = max(sum, ml);
}
// Move rightwards
for (i = m + , sum = ; i <= r; i++) {
sum += nums[i];
mr = max(sum, mr);
}
return max(smax, max(ml + mr + nums[m], max(lm, rm)));
}
};
最新文章
- cAdvisor0.24.1+InfluxDB0.13+Grafana4.0.2搭建Docker1.12.3 Swarm集群性能监控平台
- APS.net controller
- Java获取Web服务器文件
- 正则和xml解析
- java反编译工具JD-GUI
- python核心编程 第二天
- mac中添加环境变量
- Java RESTful Web Service相关概念
- iOS NSNotificationCenter 移除通知带来的crash
- Python实现XML文件解析
- sql统计总和和各状态数
- Leetcode_257_Binary Tree Paths
- C++何时需要NEW对象,new和定义对象的区别
- Unity3D UGUI实现Toast
- EntityFramework Core并发深挖详解,一纸长文,你准备好看完了吗?
- HDU 4500 小Q系列故事——屌丝的逆袭(简单题)
- AngularJS通过$location获取及改变当前页面的URL
- centor os 安装nginx
- Using KernelShark to analyze the real-time scheduler【转】
- Luogu 4433 [COCI2009-2010#1] ALADIN