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

最新文章

  1. cAdvisor0.24.1+InfluxDB0.13+Grafana4.0.2搭建Docker1.12.3 Swarm集群性能监控平台
  2. APS.net controller
  3. Java获取Web服务器文件
  4. 正则和xml解析
  5. java反编译工具JD-GUI
  6. python核心编程 第二天
  7. mac中添加环境变量
  8. Java RESTful Web Service相关概念
  9. iOS NSNotificationCenter 移除通知带来的crash
  10. Python实现XML文件解析
  11. sql统计总和和各状态数
  12. Leetcode_257_Binary Tree Paths
  13. C++何时需要NEW对象,new和定义对象的区别
  14. Unity3D UGUI实现Toast
  15. EntityFramework Core并发深挖详解,一纸长文,你准备好看完了吗?
  16. HDU 4500 小Q系列故事——屌丝的逆袭(简单题)
  17. AngularJS通过$location获取及改变当前页面的URL
  18. centor os 安装nginx
  19. Using KernelShark to analyze the real-time scheduler【转】
  20. Luogu 4433 [COCI2009-2010#1] ALADIN

热门文章

  1. sql server数据库查询超时报错
  2. COM方式实现C++调用C#代码的一些总结
  3. iOS开发之使用AFN上传图片
  4. Nokia Imaging SDK 的高级使用—实时滤镜拍照
  5. JDK默认使用的垃圾回收器
  6. boost准模板库内存管理中pool和object_pool的使用
  7. 大数据(10) - HBase的安装与使用
  8. Insert插入语句中带有select语句
  9. 精心收集的Hadoop学习资料(持续更新)
  10. 我为什么喜欢Go语言123123