Created
July 2, 2014 22:36
-
-
Save jremmen/9d16e435c4e895d1f09d to your computer and use it in GitHub Desktop.
js: maximum sub array solution using divide and conquer
This file contains 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
// O(n log n) | |
Array.prototype.submax = function() { | |
if(this.length === 0) return 0; | |
if(this.length === 1) return this[0]; | |
var m = Math.floor(this.length / 2); | |
var max_left = find_max(this, m - 1, 0); | |
var max_right = find_max(this, m, this.length); | |
function find_max(a, s, e) { | |
var max = sum = 0; | |
for(var i = s; s < e ? i < e : i >= e; s < e ? i++ : i--) { | |
sum += a[i]; | |
max = Math.max(max, sum); | |
} | |
return max; | |
} | |
var center = max_left + max_right; | |
var left = this.slice(0, m).submax() | |
var right = this.slice(m).submax() | |
return Math.max(left, center, right); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment