From 3a8e33626277146353d3ab60747e2af22fd3d25a Mon Sep 17 00:00:00 2001 From: Abhijeet Tiwari Date: Wed, 6 Oct 2021 14:45:07 +0530 Subject: [PATCH] added documentation, js standard style and jest testing to kadane algorithm file. --- Dynamic-Programming/KadaneAlgo.js | 27 +++++++++++++++----- Dynamic-Programming/tests/KadaneAlgo.test.js | 8 ++++++ 2 files changed, 29 insertions(+), 6 deletions(-) create mode 100644 Dynamic-Programming/tests/KadaneAlgo.test.js diff --git a/Dynamic-Programming/KadaneAlgo.js b/Dynamic-Programming/KadaneAlgo.js index 1e275dd09..5d60103f9 100644 --- a/Dynamic-Programming/KadaneAlgo.js +++ b/Dynamic-Programming/KadaneAlgo.js @@ -1,20 +1,35 @@ -function KadaneAlgo (array) { +/* Kadane's algorithm is one of the most efficient ways to + * calculate the maximum contiguos subarray sum for a given array. + * Below is the implementation of kadanes's algorithm along with + * some sample test cases. + * There might be a special case in this problem if al the elements + * of the given array are negative. In such a case, the maximum negative + * value present in the array is the answer. + * + * Reference article :- https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ + */ + +function kadaneAlgo (array) { let cummulativeSum = 0 - let maxSum = 0 + let maxSum = Number.NEGATIVE_INFINITY // maxSum has the least posible value for (let i = 0; i < array.length; i++) { cummulativeSum = cummulativeSum + array[i] - if (cummulativeSum < 0) { - cummulativeSum = 0 - } else if (maxSum < cummulativeSum) { + if (maxSum < cummulativeSum) { maxSum = cummulativeSum + } else if (cummulativeSum < 0) { + cummulativeSum = 0 } } return maxSum // This function returns largest sum contiguous sum in a array } function main () { + // input array const myArray = [1, 2, 3, 4, -6] - const result = KadaneAlgo(myArray) + // calling the function + const result = kadaneAlgo(myArray) + // result is the variable for storing the ourput of kadaneAlgo function console.log(result) } main() +module.exports = { kadaneAlgo } diff --git a/Dynamic-Programming/tests/KadaneAlgo.test.js b/Dynamic-Programming/tests/KadaneAlgo.test.js new file mode 100644 index 000000000..e0b7e6fd4 --- /dev/null +++ b/Dynamic-Programming/tests/KadaneAlgo.test.js @@ -0,0 +1,8 @@ +const fc = require('../kadaneAlgo') +test('test1', () => { + expect(fc.kadaneAlgo([1, 2, 3, 4, 5])).toBe(15) +}) + +test('test2', () => { + expect(fc.kadaneAlgo([-1, -2, -3, -4, 5])).toBe(5) +})