Given an integer array nums, find the subarray with the largest sum, and return its sum.
Challenge: https://leetcode.com/problems/maximum-subarray/.
Solution (using TypeScript):
Initially we have 2 variables, the first sum
to store the sum of subarray and acc
to accumulate the sum of each elements in the given array. And in the case acc
is upper than sum
, sum
takes its value.
Sample Code:
function maxSubArray(nums: number[]) {
let sum: number = nums[0];
let acc: number = 0;
nums.forEach((n: number) => {
acc = acc + n;
if (sum < acc) {
sum = acc;
}
if (acc < 0) {
acc = 0;
}
});
return sum;
}
By Ismael Messa