Leetcode 53. Maximum Subarrayjava Language

Source: Internet
Author: User

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 [4,-1,2,1] have the largest sum = 6.

Test instructions: To find the largest and most contiguous sub-arrays

Public class solution {    public int maxsubarray (int[] nums )  {        int len=nums.length;         if (nums==null | |  len==0) return 0;         int max=nums[0];          int curSum=nums[0];          for (int i=1;i<len;i++) {              if (cursum>0) {                  curSum+=nums[i];              }else{                  cursum=nums[i];          &nBsp;  }             max=math.max ( Cursum,max);         }          return max;            }}

PS: The first way of thinking, gradually accumulate cycle.

There is also a way of thinking that can be done with dynamic planning.

Public class solution {    public int maxsubarray (int[] nums )  {        int len=nums.length;         if (nums==null | |  len==0) Return 0;        //dp[i] represents the largest and at the end of Nums[i].         int[] dp=new int[len];         dp[0]=nums[0];        int MAX=dp[0];         for (int i=1;i<len;i++) {             if (dp[i-1]<0) {                 dp[i]=nums[i];             }else{                dp[i]=dp[i-1]+nums[i];             }            max=math.max (Dp[i],MAX);         }        return MAX;     }}


Leetcode 53. Maximum Subarrayjava Language

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.