// Please find the subarray with maximal sum (a) - linear solution, (b) - using prefix sums approach
function maxSumSubarray(arr) {
let n = arr.length;
// init min prefix sum to 0.
let min_prefix_sum = 0;
// initialize min subarray sum so far to -infinity.
let res = -Infinity;
// init and compute the prefix sum array.
let prefix_sum = [];
prefix_sum[0] = arr[0];
for (let i = 1; i < n; i++) {
prefix_sum[i] = prefix_sum[i - 1] + arr[i];
}
// loop through the array, keep
// track of min prefix sum so
// far and max subarray sum.
for (let i = 0; i < n; i++) {
res = Math.max(res, prefix_sum[i] - min_prefix_sum);
min_prefix_sum = Math.min(min_prefix_sum, prefix_sum[i]);
}
return res;
}
let arr1 = [ -2, -3, 4, -1, -2, 1, 5, -3 ];
console.log(maxSumSubarray(arr1));
let arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ];
console.log(maxSumSubarray(arr2));
function maxSubArrSum(a) {
let max_so_far = a[0];
let curr_max = a[0];
for (let i = 1; i < a.length; i++) {
curr_max = Math.max(a[i], curr_max + a[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
console.log(maxSubArrSum(arr1));
console.log(maxSubArrSum(arr2));