Skip to content

Instantly share code, notes, and snippets.

@jremmen
Created July 2, 2014 22:36
Show Gist options
  • Save jremmen/9d16e435c4e895d1f09d to your computer and use it in GitHub Desktop.
Save jremmen/9d16e435c4e895d1f09d to your computer and use it in GitHub Desktop.
js: maximum sub array solution using divide and conquer
// 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