Skip to content

Commit 3a8e336

Browse files
committed
added documentation, js standard style and jest testing to kadane algorithm file.
1 parent 2e6f8ae commit 3a8e336

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

Dynamic-Programming/KadaneAlgo.js

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,35 @@
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) {
213
let cummulativeSum = 0
3-
let maxSum = 0
14+
let maxSum = Number.NEGATIVE_INFINITY // maxSum has the least posible value
415
for (let i = 0; i < array.length; i++) {
516
cummulativeSum = cummulativeSum + array[i]
6-
if (cummulativeSum < 0) {
7-
cummulativeSum = 0
8-
} else if (maxSum < cummulativeSum) {
17+
if (maxSum < cummulativeSum) {
918
maxSum = cummulativeSum
19+
} else if (cummulativeSum < 0) {
20+
cummulativeSum = 0
1021
}
1122
}
1223
return maxSum
1324
// This function returns largest sum contiguous sum in a array
1425
}
1526
function main () {
27+
// input array
1628
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
1832
console.log(result)
1933
}
2034
main()
35+
module.exports = { kadaneAlgo }
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const fc = require('../kadaneAlgo')
2+
test('test1', () => {
3+
expect(fc.kadaneAlgo([1, 2, 3, 4, 5])).toBe(15)
4+
})
5+
6+
test('test2', () => {
7+
expect(fc.kadaneAlgo([-1, -2, -3, -4, 5])).toBe(5)
8+
})

0 commit comments

Comments
 (0)