[LeetCode-interview algorithm classic-Java implementation] [053-Maximum Subarray (Maximum sub-array and)],-Skip ubarray
[053-Maximum Subarray (Maximum sub-array and )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
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]
,
The contiguous subarray[4,−1,2,1]
Has the largest sum =6
.
Theme
Returns the sum of the largest sub-array of the array.
Solutions
The maximum subsequence of the first k elements is known as maxSub (recorded), and a temporary and sum. If the element k + 1 is added, because it is a continuous subsequence, if the sum of the elements before k + 1 is less than 0, therefore, there is no contribution to increasing k + 1 to form the largest subsequence, so sum can be set to 0.
Code Implementation
Algorithm Implementation class
Public class Solution {public int maxSubArray (int [] nums) {// parameter verification if (nums = null | nums. length <1) {throw new IllegalArgumentException ();} int max = Integer. MIN_VALUE; int curSum = 0; for (int I: nums) {// current and less than 0, the current value is assigned to curSum if (curSum <= 0) {curSum = I;} // otherwise, accumulate else {curSum + = I;} // save a large value if (max <curSum) {max = curSum ;}} return max ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting at http://blog.csdn.net/derrantcm/article/details/47120.pdf]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.