|
1 | | -function KadaneAlgo (array) { |
| 1 | +/* Kadane's algorithm is one of the most efficient ways to |
| 2 | + * calculate the maximum contiguos subarray sum for a given array. |
| 3 | + * Below is the implementation of kadanes's algorithm along with |
| 4 | + * some sample test cases. |
| 5 | + * There might be a special case in this problem if al the elements |
| 6 | + * of the given array are negative. In such a case, the maximum negative |
| 7 | + * value present in the array is the answer. |
| 8 | + * |
| 9 | + * Reference article :- https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ |
| 10 | + */ |
| 11 | + |
| 12 | +export function kadaneAlgo (array) { |
2 | 13 | let cummulativeSum = 0
|
3 | | - let maxSum = 0 |
| 14 | + let maxSum = Number.NEGATIVE_INFINITY// maxSum has the least posible value |
4 | 15 | for (let i = 0; i < array.length; i++) {
|
5 | 16 | cummulativeSum = cummulativeSum + array[i]
|
6 | | - if (cummulativeSum < 0) { |
7 | | - cummulativeSum = 0 |
8 | | - } else if (maxSum < cummulativeSum) { |
| 17 | + if (maxSum < cummulativeSum) { |
9 | 18 | maxSum = cummulativeSum
|
| 19 | + } else if (cummulativeSum < 0) { |
| 20 | + cummulativeSum = 0 |
10 | 21 | }
|
11 | 22 | }
|
12 | 23 | return maxSum
|
13 | 24 | // This function returns largest sum contiguous sum in a array
|
14 | 25 | }
|
15 | | -function main () { |
16 | | - const myArray = [1, 2, 3, 4, -6] |
17 | | - const result = KadaneAlgo(myArray) |
18 | | - console.log(result) |
19 | | -} |
20 | | -main() |
|
0 commit comments