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

[LeetCode系列]最大连续子列递归求解分析

时间:2014-07-31 19:47:57      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   cti   ar   

本文部分参考Discuss: LeetCode.

步骤1. 选择数组的中间元素. 最大子序列有两种可能: 包含此元素/不包含.

步骤2.

  步骤2.1 如果最大子序列不包含中间元素, 就对左右子序列进行步骤1.

  步骤2.2 如果最大子序列包含, 则结果很简单, 就是左子列的最大后缀子列(即包含左子列最后一个元素--中间元素)加上右子列的最大前缀子列(即包含右子列第一个元素--中间元素)

步骤3. 返回三者中的最大值(左子列最大值, 右子列最大值, 二者拼接最大值).

 1 class Solution {
 2 public:
 3     int maxSubArray(int A[], int n) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         if(n==0) return 0;
 7         return maxSubArrayHelperFunction(A,0,n-1);
 8     }
 9 
10     int maxSubArrayHelperFunction(int A[], int left, int right) {
11         if(right == left) return A[left];
12         int middle = (left+right)/2;
13         int leftans = maxSubArrayHelperFunction(A, left, middle);
14         int rightans = maxSubArrayHelperFunction(A, middle+1, right);
15         int leftmax = A[middle];
16         int rightmax = A[middle+1];
17         int temp = 0;
18         for(int i=middle;i>=left;i--) {
19             temp += A[i];
20             if(temp > leftmax) leftmax = temp;
21         }
22         temp = 0;
23         for(int i=middle+1;i<=right;i++) {
24             temp += A[i];
25             if(temp > rightmax) rightmax = temp;
26         }
27         return max(max(leftans, rightans),leftmax+rightmax);
28     }
29 };

 

[LeetCode系列]最大连续子列递归求解分析,布布扣,bubuko.com

[LeetCode系列]最大连续子列递归求解分析

标签:style   blog   http   color   io   for   cti   ar   

原文地址:http://www.cnblogs.com/lancelod/p/3881093.html

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