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刷题总结系列][Dynamic programming][Divide-and-conquer]53.Maximum Subarray

leetcode 53.Maximum Subarray Find a continguous subarray within an array (containing at least one nu...

※ Leetcode - Dynamic Programming - 53.Maximum Subarray(最大连续和)+152.Maximum Product Subarray(最大连续积)

1. Problem Description of 53.Maximum Subarray Find the contiguous subarray within an array (contain...

LeetCode-Easy部分中标签为Array#414 : Third Maximum Number

找数组中第n个最大值

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

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

LeetCode(53) Maximum Subarray

题目Find the contiguous subarray within an array (containing at least one number) which has the larges...
  • fly_yr
  • fly_yr
  • 2015年09月05日 20:35
  • 744

leetcode刷题之旅——53. Maximum Subarray

本周写的第二道分治算法的题目,因为上次选择的是一道easy的题目,为了提升自己,这次选择了一道middle难度的题目。虽然这道题目是middle的,但是我还是想了很长时间。其实这道题目可以用动态规划直...

[LeetCode]53.Maximum Subarray

【题目】 Find the contiguous subarray within an array (containing at least one number) which has the l...

53.Maximum Subarray | LeetCode 解题思路

本题来源于LeetCode devide and conquer题库,难度easy。

Leetcode53 Maximum Subarray

Maximum Subarray Find the contiguous subarray within an array (containing at least one number) whi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode-Easy部分中标签为 Dynamic Programming(DP) 53. Maximum Subarray
举报原因:
原因补充:

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