Skip to content

Commit 100ace7

Browse files
committed
add JavaScript code for Kadan's algorithm
1 parent 8455aba commit 100ace7

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

Kadane's/JavaScript/kedane.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Calculates the largest sum of contiguous subarray within a one-dimensional array
3+
* @param {Array} array - One-dimensional array
4+
* @return {Number} currentMax - The largest sum of contiguous subarrays
5+
*/
6+
function kadane(array){
7+
var currentMax = max = 0;
8+
for (var i = 0; i < array.length; i++) {
9+
max = Math.max(0, max + array[i]);
10+
currentMax = Math.max(currentMax, max);
11+
}
12+
return currentMax;
13+
}
14+
15+
var array = [-2, -3, 4, -1, -2, 1, 5, -3];
16+
console.log("Maximum contiguous sum is: " + kadane(array));

0 commit comments

Comments
 (0)