Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 64d005e

Browse files
committedJan 16, 2025
Added Kadane's Algorithm implementation and test cases
1 parent ca3d16d commit 64d005e

File tree

4 files changed

+32
-2
lines changed

4 files changed

+32
-2
lines changed
 

‎package-lock.json

+2-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
"eslint-plugin-jest": "27.2.1",
4545
"eslint-plugin-jsx-a11y": "6.7.1",
4646
"husky": "8.0.3",
47-
"jest": "29.4.1",
47+
"jest": "^29.4.1",
4848
"pngjs": "^7.0.0"
4949
},
5050
"engines": {

‎src/algorithms/kadane-algorithm.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function kadaneAlgorithm(arr) {
2+
let sum = 0;
3+
let maxi = 0;
4+
5+
for (let i = 0; i < arr.length; i++) {
6+
sum += arr[i];
7+
maxi = Math.max(sum, maxi);
8+
9+
if (sum < 0) {
10+
sum = 0;
11+
}
12+
}
13+
14+
return maxi;
15+
}
16+
17+
module.exports = kadaneAlgorithm;

‎src/tests/kadane-algorithm.test.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const kadaneAlgorithm = require('C:/Users/Muskan/Documents/javascript-algorithms/src/algorithms/kadane-algorithm.js');
2+
3+
describe("Kadane's Algorithm", () => {
4+
it('should return the maximum subarray sum', () => {
5+
const result = kadaneAlgorithm([1, -2, 3, -1, 2, 1, -5, 4]);
6+
console.log(result);
7+
expect(kadaneAlgorithm([1, -2, 3, -1, 2, 1, -5, 4])).toBe(5);
8+
expect(kadaneAlgorithm([-2, 1, -3, 4, -1, 2, 1, -5, 4])).toBe(6);
9+
expect(kadaneAlgorithm([1, 2, 3, 4, 5])).toBe(15);
10+
expect(kadaneAlgorithm([-1, -2, -3, -4])).toBe(0);
11+
});
12+
});

0 commit comments

Comments
 (0)
Please sign in to comment.