[Leetcode]53. Maximum Subarray maximum sub-array and

Source: Internet
Author: User

Given an integer array nums , find the contiguous subarray (containing at least one number) which have the largest sum and return its sum.

Example:

Input: [ -2,1,-3,4,-1,2,1,-5,46Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you had figured out the O (n) solution, try coding another solution using the divide and conquer approach, WHI CH is more subtle.

Test instructions

To find the largest subarray and

Ideas:

One-dimensional DP

Principle: Any number plus negative is definitely smaller than the original value

Dp[i] Indicates the maximum value that can be taken by the first element

Dp[i] = dp[i-1] >0? DP[I-1] + num[i]: num[i]

Code:

1 classSolution {2      Public intMaxsubarray (int[] nums) {3         int[] DP =New int[nums.length];4Dp[0] = nums[0];5         intMaxresult = Nums[0];6         7          for(inti = 1; i < nums.length; i++){8Dp[i] = Dp[i-1] > 0? DP[I-1] +Nums[i]: nums[i];9Maxresult =Math.max (Maxresult, dp[i]);Ten         } One         returnMaxresult;  A     } -}

[Leetcode]53. 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.