Skip to content

Instantly share code, notes, and snippets.

@Dammmien
Created February 15, 2016 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dammmien/1e8c0ab67ddec808879b to your computer and use it in GitHub Desktop.
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.
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