Maximum Subarray
Problem
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1] Output: 1
Example 3:
Input: nums = [5,4,-1,7,8] Output: 23
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
Solution
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let max = nums[0];
const dp = [max];
for (let i = 1; i < nums.length; i++) {
if (dp[i - 1] > 0) {
dp.push(nums[i] + dp[i - 1]);
} else {
dp.push(nums[i]);
}
max = Math.max(max, dp[i]);
}
return max;
};
We will implement a DP solution. Let dp[i]
be the largest sum of the contiguous subarray ending and including nums[i]
.
- For the base case, if
i = 0
, thendp[0] = nums[0]
since there's only a single element ofnums
available. - For the recursive case:
- If the previous largest sum
dp[i - 1]
is non-negative, the next max sum which includesnums[i]
must benums[i] + dp[i - 1]
(since adding a non-negative number will never result in a smaller value). - If the previous largest sum
dp[i - 1]
is negative, the next max sum which includesnums[i]
must benums[i]
itself (since adding a negative number will always result in a smaller value).
- If the previous largest sum