码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Maximum Subarray[dp]

时间:2017-07-09 17:17:26      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:状态   etc   style   标签   代码   ide   using   ini   not   

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.

click to show more practice.

More practice:

 

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 

标签: Divide and Conquer Array Dynamic Programming

分析:最大连续子和问题,我们可以从头遍历数组,遍历到元素 i 时有两个选择:

1.如果它大于等于零时,那就将它与前面的子和sum相加。

2.如果它小于零时,则由该元素作为下一个子和sum的开头元素

在遍历数组的同时记录最大的子和sumj即为最大连续子和;

这里用动态规划的方法解决,设dp[i]表示从首元素到元素i的最大连续子和,所以有状态转移方程为:

dp[i]=max(dp[i-1]+array[i],array[i]);

参考代码:

 1 public class Solution {
 2     public int maxSubArray(int[] A) {
 3         int len=A.length;
 4         int ret=Integer.MIN_VALUE;
 5         int dp=0;
 6         for(int i=0;i<len;i++){
 7             dp=Math.max(dp+A[i], A[i]);
 8             ret=Math.max(ret, dp);
 9         }
10         return ret;
11     }
12 }

 

LeetCode-Maximum Subarray[dp]

标签:状态   etc   style   标签   代码   ide   using   ini   not   

原文地址:http://www.cnblogs.com/xiaolu266/p/7141751.html

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