[LeetCode-interview algorithm classic-Java implementation] [053-Maximum Subarray (Maximum sub-array and)],-Skip ubarray

Source: Internet
Author: User

[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.

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.