Created
September 9, 2017 18:11
-
-
Save lucas1richard/460c19a5bbbbfcbac3880800a239e61f to your computer and use it in GitHub Desktop.
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
const Heap = require('heap'); | |
/** | |
* Combine sticks, while adding the sums, to get the lowest combined sum possible | |
* @param {[number]} sticks - array of lengths | |
* @return {number} | |
*/ | |
function combineSumSticks(sticks) { | |
const heap = new Heap(); | |
var totalSum = 0; | |
sticks.forEach(stick => heap.push(stick)); | |
var smStick, smallStick; | |
while (heap.peek()) { | |
smStick = heap.pop(); | |
smallStick = heap.pop(); | |
if (!smStick || !smallStick) { | |
break; | |
} | |
var sumStick = smStick + smallStick; | |
totalSum += sumStick; | |
heap.push(sumStick); | |
} | |
return totalSum; | |
} | |
combineSumSticks([1, 2, 3, 4]); // 19 | |
combineSumSticks([1, 2, 3, 4, 5]); // 33 | |
combineSumSticks([1, 2, 3, 4, 5, 6]); // 51 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment