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]
,
[4,-1,2,1]
has the largest sum = 6
. 思路:
ref:https://discuss.leetcode.com/topic/6413/dp-solution-some-thoughts
这个做法和我的想法很接近,里面讲的有些思路很清晰很直接。
我是直接用最小的例子来分析。
-2,
-2,1
-2,1,-3
dp[0]<0,dp[1]=nums[1]
dp[0]>0,dp[1]=dp[0]+nums[1];
找最大的dp。
public class Solution { public int maxSubArray(int[] nums) { int[] dp=new int[nums.length]; dp[0]=nums[0]; int max=dp[0]; for(int i=1;i