码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-04-05 15:51:33      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:turn   find   content   new   which   tab   nta   最大子数组   规划   

 

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(动态规划 求最大子数组)

标签:turn   find   content   new   which   tab   nta   最大子数组   规划   

原文地址:https://www.cnblogs.com/zle1992/p/8722797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!