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

Maximum Subarray

时间:2014-08-26 22:44:46      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   log   amp   

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.

思路:依次遍历输入数组,若i-1处的和curMax为正,则i处的和应为curMax + A[i];否则,i处的和为A[i]本身,此时,前i-1个数不会对i及后续数的最大和产生影响。

 1 class Solution {
 2 public:
 3     int maxSubArray( int A[], int n ) {
 4         int maxSum = A[0], curMax = A[0];
 5         for( int i = 1; i < n; ++i ) {
 6             curMax = curMax < 0 ? A[i] : curMax + A[i];
 7             if( maxSum < curMax ) { maxSum = curMax; }
 8         }
 9         return maxSum;
10     }
11 };

 

Maximum Subarray

标签:style   blog   color   io   for   ar   div   log   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3938244.html

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