Skip to content

Instantly share code, notes, and snippets.

@lucas1richard
Created September 9, 2017 18:11
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 lucas1richard/460c19a5bbbbfcbac3880800a239e61f to your computer and use it in GitHub Desktop.
Save lucas1richard/460c19a5bbbbfcbac3880800a239e61f to your computer and use it in GitHub Desktop.
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