"Leetcode-Interview algorithm classic-java Implementation" "053-maximum Subarray (maximum sub-array and)"

Source: Internet
Author: User

"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)"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.