"053-maximum subarray (maximum sub-array and)""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question
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 .
Main Topic
The maximum number of sub-arrays of the array.
Thinking of solving problems
Dynamic programming problem, it is known that the maximum subsequence of the first k elements and for Maxsub (has been recorded), as well as a temporary sum, if the element k+1 is added, because it is a continuous sub-sequence of this restriction, so if k+1 this element before and is less than 0, then for the increase of K + 1 This element thus to make the largest subsequence is not contributing, so the sum can be placed 0.
Code Implementation
Algorithm implementation class
Public classSolution { Public int Maxsubarray(int[] nums) {//Parameter check if(Nums = =NULL|| Nums.length <1) {Throw NewIllegalArgumentException (); }intmax = Integer.min_value;intCursum =0; for(intI:nums) {//current and less than 0, assign the current value to Cursum if(Cursum <=0) {cursum = i; }//otherwise accumulate Else{cursum + = i; }//Save a larger value if(Max < Cursum) {max = cursum; } }returnMax }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47120487"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "053-maximum Subarray (maximum sub-array and)"