本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

LeetCode:Maximum Subarray

题目链接

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.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


可以参考我的另一篇博文最大子数组和(最大子段和)

下面分别给出O(n)的动态规划解法和O(nlogn)的分治解法                              本文地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    int maxSubArray(int A[], int n) {
        //最大字段和问题
        int res = INT_MIN, sum = -1;
        for(int i = 0; i < n; i++)
        {
            if(sum > 0)
                sum += A[i];
            else sum = A[i];
            if(sum > res)res = sum;
        }
        return res;
    }
};

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    int maxSubArray(int A[], int n) {
        //最大字段和问题
        return helper(A, 0, n-1);
    }
private:
    int helper(int A[], const int istart, const int iend)
    {
        if(istart == iend)return A[iend];
        int middle = (istart + iend) / 2;
        int maxLeft = helper(A, istart, middle);
        int maxRight = helper(A, middle + 1, iend);
        int midLeft = A[middle];
        int tmp = midLeft;
        for(int i = middle - 1; i >= istart; i--)
        {
            tmp += A[i];
            if(midLeft < tmp)midLeft = tmp;
        }
        int midRight = A[middle + 1];
        tmp = midRight;
        for(int i = middle + 2; i <= iend; i++)
        {
            tmp += A[i];
            if(midRight < tmp)midRight = tmp;
        }
        return max(max(maxLeft, maxRight), midLeft + midRight);
    }
};

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3713525.html

posted @   tenos  阅读(898)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
· 程序员转型AI:行业分析
· 重磅发布!DeepSeek 微调秘籍揭秘,一键解锁升级版全家桶,AI 玩家必备神器!

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童

点击右上角即可分享
微信分享提示