JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
// Start with the max sum being the first value.
const S = [nums[0]];
// Store the first value so that we can output the substring of values.
const V = [[nums[0]]];
let maxIndex = 0;
for (let i=1; i<nums.length; i++) {
// Increment the sum if the previous value is greater than 0, otherwise reset the count.
S[i] = nums[i] + Math.max(0, S[i-1]);
// Append the value if the previous value is greater than 0, otherwise reset the substring.
V[i] = S[i-1] > 0 ? [...(V[i-1])] : [];
V[i].push(nums[i]);
// Record the max value.
maxIndex = S[i] > S[maxIndex] ? i : maxIndex;
}
console.log(V[maxIndex]);
return S[maxIndex];
};
console.log(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]));