Skip to content

Instantly share code, notes, and snippets.

@hawaijar
Created August 17, 2022 04:32
Show Gist options
  • Save hawaijar/f8cf21e9a779cafe012cea417836b259 to your computer and use it in GitHub Desktop.
Save hawaijar/f8cf21e9a779cafe012cea417836b259 to your computer and use it in GitHub Desktop.
Kadane's Algorithm
//Given an array of integers (containing positive and negative value),
// find the maximum sum of a contiguous SubArray.
// Detail: https://github.com/hawaijar/FireLeetcode/blob/feature/algoexpert/Famous%20Algorithms/KadaneAlgorithm/README.md
(() => {
function kadaneAlgorithm(array: number[]) {
// base case
if (array.length === 0) {
return 0;
}
if (array.length <= 1) {
return array[0];
}
let largestSum = -Infinity;
let previousMaxSum = 0;
for (let number of array) {
previousMaxSum = previousMaxSum + number;
if (previousMaxSum < 0) {
// case: for all negative numbers scenario
largestSum = Math.max(largestSum, previousMaxSum);
// exclude the number and start again
previousMaxSum = 0;
} else {
largestSum = Math.max(largestSum, previousMaxSum);
}
}
return largestSum;
}
// Testing
const array = [1, -3, 3];
console.log(kadaneAlgorithm(array));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment