forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemove Stones to Minimize the Total.js
55 lines (47 loc) · 1.38 KB
/
Remove Stones to Minimize the Total.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @param {number[]} piles
* @param {number} k
* @return {number}
*/
var minStoneSum = function(piles, k) {
var heapArr = [];
for (let i=0; i<piles.length; i++){
heapArr.push(piles[i]);
heapifyUp();
}
function heapifyUp(){
let currIndex = heapArr.length-1;
while (heapArr[currIndex] > heapArr[Math.floor((currIndex-1)/2)]){
swap(currIndex, Math.floor((currIndex-1)/2));
currIndex = Math.floor((currIndex-1)/2);
}
}
function heapifyDown(){
let currIndex = 0;
let bigger = currIndex;
while (heapArr[currIndex*2+1]){
if (heapArr[currIndex] < heapArr[currIndex*2+1]){
bigger = currIndex * 2 + 1;
}
if (heapArr[bigger] < heapArr[currIndex*2+2]){
bigger = currIndex * 2 + 2;
}
if (bigger === currIndex){
break;
}
swap(currIndex, bigger);
currIndex = bigger;
}
}
function swap(currIndex, otherIndex){
let temp = heapArr[currIndex];
heapArr[currIndex] = heapArr[otherIndex];
heapArr[otherIndex] = temp;
}
while (k > 0){
heapArr[0] -= Math.floor(heapArr[0]/2);
heapifyDown();
k--;
}
return heapArr.reduce((a,num) => a+num, 0);
};