Created
May 1, 2023 14:45
-
-
Save cmgchess/bbb43b02b01bcc7642ce83010ea91b9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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