Skip to content

Instantly share code, notes, and snippets.

@cmgchess
Created May 1, 2023 14:45
Show Gist options
  • Save cmgchess/bbb43b02b01bcc7642ce83010ea91b9d to your computer and use it in GitHub Desktop.
Save cmgchess/bbb43b02b01bcc7642ce83010ea91b9d to your computer and use it in GitHub Desktop.
function maxSubarrayCrossingSum(arr, left, right, mid) {
let leftSum = -Infinity;
let currentSum = 0;
for (let i = mid; i >= left; i--) {
currentSum += arr[i];
if (currentSum > leftSum) leftSum = currentSum;
}
let rightSum = -Infinity;
currentSum = 0;
for (let i = mid + 1; i <= right; i++) {
currentSum += arr[i];
if (currentSum > rightSum) rightSum = currentSum;
}
return leftSum + rightSum;
}
function maxSubarraySum(arr, left, right) {
if (left === right) return arr[left];
const mid = Math.floor((left + right) / 2);
return Math.max(
Math.max(maxSubarraySum(arr, left, mid), maxSubarraySum(arr, mid + 1, right)),
maxSubarrayCrossingSum(arr, left, right, mid)
);
}
const a1= [1, -2, 3, 10, -4, 7, 2, -5];
const a2 = [-1, -2, -3, -4, -5];
const a3 = [4, 2, 2, 1, 5, 3];
console.log(maxSubarraySum(a1,0,a1.length-1));
console.log(maxSubarraySum(a2,0,a2.length-1));
console.log(maxSubarraySum(a3,0,a3.length-1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment