Skip to content

Commit 6eeb989

Browse files
authored
chore: Merge pull request #750 from thisabhijeet/kadanes
added documentation, js standard style and jest testing to kadane algorithm file.
2 parents 7c9219d + ed49e12 commit 6eeb989

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

Diff for: Dynamic-Programming/KadaneAlgo.js

+16-11
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
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) {
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
}
15-
function main () {
16-
const myArray = [1, 2, 3, 4, -6]
17-
const result = KadaneAlgo(myArray)
18-
console.log(result)
19-
}
20-
main()

Diff for: Dynamic-Programming/tests/KadaneAlgo.test.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { kadaneAlgo } from '../KadaneAlgo'
2+
test('it is being checked that 15 is the answer to the corresponding array input', () => {
3+
expect(kadaneAlgo([1, 2, 3, 4, 5])).toBe(15)
4+
})
5+
6+
test('it is being checked that 5 is the answer to the corresponding array input', () => {
7+
expect(kadaneAlgo([-1, -2, -3, -4, 5])).toBe(5)
8+
})

0 commit comments

Comments
 (0)