首页 > 其他 > 详细

LeetCode - Maximum Subarray

时间:2014-11-19 17:45:23      阅读:181      评论:0      收藏:0      [点我收藏+]

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

如果当前的和小于0,则在后面的数加上现在的和只会比原来的数要小,故舍弃

DP的思路:
O(n)就是一维DP。
假设A(0, i)区间存在k,使得[k, i]区间是以i结尾区间的最大值,定义为Max[i],当求取Max[i+1]时,
bubuko.com,布布扣
然后从左往右扫描,求取Max数字的最大值即为所求。
 1 class Solution {
 2 public:
 3     int maxSubArray(int A[], int n) {
 4         int ans = 0;
 5         int maxsum = INT_MIN;
 6         
 7         for (int i = 0; i < n; i++)
 8         {
 9             if (ans < 0)
10                 ans = 0;
11             ans += A[i];
12             maxsum = max(ans, maxsum);
13         }
14         return maxsum;
15     }
16 };

 

LeetCode - Maximum Subarray

原文:http://www.cnblogs.com/bournet/p/4108624.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!