Find the contiguous subarray within an array (containing at least one number) which have the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
The contiguous Subarray has the [4,−1,2,1]
largest sum = 6
.
Click to show more practice.
More Practice:
If you had figured out the O (n) solution, try coding another solution using the divide and conquer approach, WHI CH is more subtle.
Solution: Dynamic Programming.sum[i] = max (Nums[i], nums[i] + sum[i-1]) The changing condition for Dynamic programming is "We s Hould ignore the sum of the previous n-1 elements if nth element is greater than the sum. "
Imagine if we were to traverse this array from the beginning. For one of the elements in an array, it has only two choices:
1. Either join the previous array plus (group with others)
2. Either set up a single array of your own (one for yourself)
So the choice of this element depends on what group he can contribute to. If you are in a group with someone else, you can always add and get bigger, or a group of others, and if you start a group, your value is larger than the value of the previous sums, then it is better to open a group alone.
So use a sum array to record the maximum value for each round of sum, Sum[i] Indicates whether the current element is the same as the previous array plus a set or a single set of itself, and then maintain a global maximum value of the throne answer.
Java Code:
The first type of notation:
Public classSolution { Public intMaxsubarray (int[] nums) { intLen =nums.length; int[] sum =New int[Len]; intmax = Nums[0]; sum[0] = Nums[0]; for(inti = 1; i< Len; i++) {Sum[i]= Math.max (Nums[i], nums[i] + sum[i-1]); Max=Math.max (Max, sum[i]); } returnMax; }}
The second way: sum does not use an array, only an int
Public class Solution { publicint maxsubarray (int[] nums) { int sum = nums[0]; int max = nums[0]; for (int i = 1; i< nums.length; i++) { = Math.max (Nums[i], nums[i] + sum); = Math.max (max, sum); } return Max;} }
Reference:
1. http://www.programcreek.com/2013/02/leetcode-maximum-subarray-java/
2. http://www.programcreek.com/2013/02/leetcode-maximum-subarray-java/
Leetcode Maximum Subarray