Authentic Preference

Technologies come and technologies go, but insight is forever.

LeetCode-Easy部分中标签为 Dynamic Programming(DP) 53. 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.

题目分析

这个题表面上看能分解为类似

MaxSubArray(int[] nums, int i, int j)

即求nums[i:j]子数组的最大值。再仔细分析后发现,找不到与原问题的契合点。

不妨换思路, maxSubArray(int[] nums, int i)
dyna[i] = nums[i] + (dyna[i-1]>0 ? dyna[i-1]:0)
max = Max(max, dyna[i])

代码实现

        public int MaxSubArray(int[] nums)
        {
            int n = nums.Length;
            int[] dyna = new int[n];
            dyna[0] = nums[0];
            int max = dyna[0];

            for (int i = 1; i < n; i++)
            {
                dyna[i] = nums[i] + (dyna[i - 1] > 0 ? dyna[i - 1] : 0);
                max = Math.Max(dyna[i], max);
            }

            return max;
        }

此题更精简的做法:
http://blog.csdn.net/daigualu/article/details/70980526

阅读更多
版权声明:本文为博主原创文章,欢迎转载,请注明 http://blog.csdn.net/daigualu https://blog.csdn.net/daigualu/article/details/69936974
个人分类: 算法/LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode-Easy部分中标签为 Dynamic Programming(DP) 53. Maximum Subarray

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭