|
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 | +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 | 26 | function main () {
|
| 27 | + // input array |
16 | 28 | const myArray = [1, 2, 3, 4, -6]
|
17 |
| - const result = KadaneAlgo(myArray) |
| 29 | + // calling the function |
| 30 | + const result = kadaneAlgo(myArray) |
| 31 | + // result is the variable for storing the ourput of kadaneAlgo function |
18 | 32 | console.log(result)
|
19 | 33 | }
|
20 | 34 | main()
|
| 35 | +module.exports = { kadaneAlgo } |
0 commit comments