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