53. Maximum Subarray(动态规划 求最大子数组)

Posted 张乐乐章

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

递归方程;

dp[i] = dp[i-1]+nums[i] ,dp[i-1]>0

dp[i] = nums[i] ,else

 1 class Solution {
 2     public int maxSubArray(int[] nums) {
 3         int dp[] = new int[nums.length+1];
 4         int max = nums[0];
 5         dp[0] = nums[0];
 6         for(int i =1;i<nums.length;i++){
 7             if(dp[i-1]<=0)
 8                 dp[i] = nums[i];
 9             else
10                 dp[i] = dp[i-1]+nums[i];
11             max = Math.max(dp[i],max);
12         }
13         return max;
14     }
15 }

 

以上是关于53. Maximum Subarray(动态规划 求最大子数组)的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]53Maximum Subarray动态规划经典题目:最大子串问题

Leetcode之动态规划(DP)专题-53. 最大子序和(Maximum Subarray)

leetcode 53. Maximum Subarray

53. Maximum Subarray

leetcode-53 maximum-subarray(最大子序和)

L53-Maximum-Subarray