Created
February 15, 2016 18:09
-
-
Save Dammmien/1e8c0ab67ddec808879b to your computer and use it in GitHub Desktop.
Kadane algorithm In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum.
For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4.
The contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = [ -2, 1, -3, 4, -1, 2, 1, -5, 4 ], | |
now = 0, | |
prev = 0; | |
for ( var i = 0; i < a.length; i++ ) { | |
prev = Math.max( 0, prev + a[ i ] ); | |
now = Math.max( prev, now ); | |
} | |
console.log( now ); // 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment