[Leetcode] [JavaScript] Maximum Subarray

Source: Internet
Author: User

Maximum Subarray

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 .

https://leetcode.com/problems/maximum-subarray/

Find out and the largest substring.

Dynamic planning, maintain a variable previous, record the maximum value before.

The current maximum value is Math.max (previous + nums[i], nums[i]).

1 /**2 * @param {number[]} nums3 * @return {number}4  */5 varMaxsubarray =function(nums) {6     if(Nums.length = = 0)return0;7     varPrevious = Math.max (0, nums[0]), max = Nums[0];8      for(vari = 1; i < nums.length; i++){9Previous = Math.max (previous +Nums[i], nums[i]);TenMax =Math.max (Previous, max); One     } A     returnMax; -};

The beginning of the writing is more verbose.

Dynamic planning, the maximum number of substrings to the current index may have three scenarios:

1. Current element, Nums[i]

2. Nums[i] + includes the maximum substring of the previous element nums[i-1] and

3. Nums[i] + previous element nums[i-1] maximum value (excluding nums[i-1]) + nums[i-1]

1 /**2 * @param {number[]} nums3 * @return {number}4  */5 varMaxsubarray =function(nums) {6     if(Nums.length = = 0)return0;7     varDP = [], max = Nums[0], previous, current;8Dp[0] = {previous:0, current:nums[0]};9      for(vari = 1; i < nums.length; i++){TenPrevious = Dp[i-1].current; OneCurrent = Math.max (Nums[i], nums[i] + dp[i-1].current, ANums[i] + nums[i-1] + dp[i-1].previous); -Dp[i] ={previous:previous, current:current}; -Max =Math.max (current, max); the     } -     returnMax; -};

[Leetcode] [JavaScript] Maximum Subarray

Related Article

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.