Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

added documentation, js standard style and jest testing to kadane algorithm file. #750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
raklaptudirm merged 4 commits into TheAlgorithms:master from thisabhijeet:kadanes
Oct 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions Dynamic-Programming/KadaneAlgo.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
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/
*/

export 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 () {
const myArray = [1, 2, 3, 4, -6]
const result = KadaneAlgo(myArray)
console.log(result)
}
main()
8 changes: 8 additions & 0 deletions Dynamic-Programming/tests/KadaneAlgo.test.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { kadaneAlgo } from '../KadaneAlgo'
test('it is being checked that 15 is the answer to the corresponding array input', () => {
expect(kadaneAlgo([1, 2, 3, 4, 5])).toBe(15)
})

test('it is being checked that 5 is the answer to the corresponding array input', () => {
expect(kadaneAlgo([-1, -2, -3, -4, 5])).toBe(5)
})

AltStyle によって変換されたページ (->オリジナル) /