Last active
August 29, 2015 14:16
-
-
Save LeeYeeze/edd842cef7b9fa679afc to your computer and use it in GitHub Desktop.
weighted task scheduling
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
function binarySearch (array, target, start, end) { | |
var l = start || 0; | |
var r = end || array.length - 1; | |
while (l<=r) { | |
var mid = Math.floor((l+r)/2); | |
if (array[mid]==target) { | |
return mid; | |
} else if (array[mid]>target) { | |
r = mid - 1; | |
} else { | |
l = mid + 1; | |
} | |
} | |
return r; | |
} | |
function weightedIntervalScheduling(taskArray) { | |
taskArray.sort(function (a,b) { | |
return a.end - b.end ==0 ? a.start - b.start: a.end - b.end; | |
}); | |
//console.log(taskArray); | |
var endArray = taskArray.map(function (obj) { | |
return obj.end; | |
}); | |
//console.log(endArray); | |
var pArray = [-1]; | |
for (var i = 1; i<taskArray.length; i++) { | |
var idx = binarySearch(endArray,taskArray[i].start,0,i-1); | |
pArray[i] = idx; | |
} | |
//console.log(pArray); | |
var res = []; | |
res[0] = taskArray[0].weight; | |
for (var i= 1; i<taskArray.length; i++) { | |
if (pArray[i]>-1) { | |
res[i] = res[pArray[i]]+taskArray[i].weight; | |
} else { | |
res[i] = taskArray[i].weight; | |
} | |
res[i] = Math.max(res[i], res[i-1]); | |
} | |
return res[res.length-1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment