[Leetcode] [Java] Maximum Subarray__java

Source: Internet
Author: User
topic:

Find the contiguous subarray within a 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. The following:

Finds the largest contiguous subsequence in an array.

For example, given an array [−2,1,−3,4,−1,2,1,−5,4],

wherein the sequential subsequence [4,−1,2,1] has the largest and 6. Algorithm Analysis:

This topic is a dynamic programming problem (DP). The maximum subsequence of the first k elements is known and the Maxsub (which has been recorded), and a temp and sum, if the element k+1 is added, because it is a continuous subsequence, so if the sum of k+1 is less than 0, then for the increase of K + 1 This element to make up the maximum subsequence is not contributing, so you can set the sum to 0. For instance,-1,-2, 4,-5, 7 it is assumed that 7 is the first K+1 element, so it is obvious that the sum =-5 + 4 =-1, then this will only reduce it for 7来, so the correct answer can be obtained directly by placing sum = 0, 0 + 7. Then expand this array,-1,-2, 4,-5, 7, 1 before sum = 1 > 7, which is a contribution to the subsequent one composing the maximum subsequence, so sum = 0 + 7 = 1. Again, as long as the sum is not reduced to a negative number, the middle of less than 0 elements are not related, sum can still continue to accumulate. The code is as follows:

public class Solution 
{public
    int maxsubarray (int[] nums) 
    {
        int sum = nums[0], maxsum = nums[0];
        for (int i = 1; i < nums.length i++)
        {
          if (sum < 0) sum = 0;   First judge whether the sum can be used this time (less than 0 is discarded)
          sum + + + nums[i];
          Maxsum = Math.max (maxsum, sum); 
        }
        Return maxsum
     }
}



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.