Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],Output: 6Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
public class MaximumSubarray{ public static int maximuntmSubarray(int[] a){ int n = n.length; int max = a[0]; int[] dp = new int[n]; dp[0] = a[0]; for(int i = 1; i < n; i++){ dp[i] = (dp[i-1]>0 ? dp[i] : 0)+a[i]; max = Math.max(max,dp[i]); } return max; }}
经典的动态规划问题。令数组dp[i]为前i个数的最大连续数之和,max初始值为a[0]。分解问题:
当前i-1个数的最大连续和为负时,那么另dp[i]=a[i];
当前i-1个数的最大连续和不为负时,另dp[i] = a[i] + dp[i-1];
最后与保存的max相比较,取最大值。