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

原创 2017年04月09日 22:03:21

原题

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 举报

相关文章推荐

LeetCode 53. Maximum Subarray(dynamic programming)

题目链接:https://leetcode.com/problems/maximum-subarray/ 题目描述: Find the contiguous subarray within an ...

LeetCode 53/152 Maximum Subarray/Maximum Product Subarray---DP **

题目:Maximum Subarray Find the contiguous subarray within an array (containing at least one number) ...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

LeetCode 53. Maximum Subarray Java

53. Maximum Subarray   Find the contiguous subarray within an array (containing ...

Leetcode 53. Maximum Subarray

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

leetcode || 53、Maximum Subarray

problem: Find the contiguous subarray within an array (containing at least one number) which h...

leetcode-53:Maximum Subarray

声明: 1、本文仅为学习笔记,不得商用 2、文中所引文献,已在参考资料中说明,但部分来源于网络,出处无可考究,如果文中引用了您的原创,请您私信我 3、如果内容有错误或者不准确的地方请大家指...

leetcode-53. Maximum Subarray

leetcode-53. Maximum Subarray题目: 我们可以考虑两种情况, 一种情况是简单的情况。也就是只要考虑单独一个到的情况。这样的情况对应于,S2的面积大于S1,说明i点之前的区域...

[LeetCode] 53. Maximum Subarray

[LeetCode] 53. Maximum Subarray(Medium) 分治算法实践

【Leetcode】53. Maximum Subarray

Description: Find the contiguous subarray within an array (containing at least one number) which ha...

[leetcode] 53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest ...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)