Topic:
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.
Analysis:
-Using dynamic programming ideas
Calculates the largest and the first n items, and the result may be as follows for newly added n+1 items
N=0: For maximum and no help
Separate a[n+1]
The resulting array is combined with Max_subarray (A[n]) and a[n+1] and the elements between them.
Among them, if in the growth process, the existing array segment and is negative, can be discarded immediately, because in this case, max_subarray if the inclusion of this paragraph, the value will certainly be greater than excluding this paragraph.
Code:
Public Static intMaxsubarray (int[] nums) { intIntresult = Nums[0]; intIntcurrentsum = Nums[0]; for(intI =1;i<nums.length;i++){ if(Intcurrentsum < 0) {intcurrentsum=Nums[i]; } Else{intcurrentsum= Intcurrentsum +Nums[i]; } if(intcurrentsum>intresult) {Intresult=intcurrentsum; } } returnIntresult; }
[Leetcode]: 53:maximum subarray