Skip to content

Commit 19eb2e9

Browse files
committed
1046 Last Stone Weight Solution
1 parent 53c3815 commit 19eb2e9

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

typescript/1046-Last-Stone-Weight.ts

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class MaxHeap {
2+
heap: number[]
3+
constructor(array: number[]) {
4+
this.heap = this.buildHeap(array)
5+
}
6+
7+
buildHeap(array: number[]) {
8+
let parentIdx = Math.floor((array.length - 2) / 2)
9+
for (let i = parentIdx; i >= 0; i--) {
10+
this.siftDown(i, array.length - 1, array)
11+
}
12+
return array
13+
}
14+
15+
siftDown(idx: number, endIdx: number, heap: number[]) {
16+
let childOneIdx = 2 * idx + 1
17+
18+
while (childOneIdx <= endIdx) {
19+
let childTwoIdx = 2 * idx + 2 <= endIdx ? 2 * idx + 2 : -1
20+
let swapIdx
21+
if (childTwoIdx !== -1 && heap[childOneIdx] < heap[childTwoIdx]) {
22+
swapIdx = childTwoIdx
23+
} else swapIdx = childOneIdx
24+
if (heap[swapIdx] > heap[idx]) {
25+
this.swap(swapIdx, idx, heap)
26+
idx = swapIdx
27+
childOneIdx = 2 * idx + 1
28+
} else return
29+
}
30+
}
31+
32+
siftUp(idx: number, heap: number[]) {
33+
let parentIdx = Math.floor((idx - 1) / 2)
34+
while (heap[parentIdx] < heap[idx] && idx > 0) {
35+
this.swap(parentIdx, idx, heap)
36+
idx = parentIdx
37+
parentIdx = Math.floor((idx - 1) / 2)
38+
}
39+
}
40+
41+
peek() {
42+
return this.heap[0]
43+
}
44+
45+
remove() {
46+
this.swap(this.heap.length - 1, 0, this.heap)
47+
const removeValue = this.heap.pop()
48+
this.siftDown(0, this.heap.length - 1, this.heap)
49+
return removeValue
50+
}
51+
52+
size() {
53+
return this.heap.length
54+
}
55+
56+
insert(value: number) {
57+
this.heap.push(value)
58+
this.siftUp(this.heap.length - 1, this.heap)
59+
}
60+
swap(i: number, j: number, arr: number[]) {
61+
let ele = arr[i]
62+
arr[i] = arr[j]
63+
arr[j] = ele
64+
}
65+
}
66+
67+
function lastStoneWeight(stones: number[]): number {
68+
const heap = new MaxHeap(stones)
69+
70+
while (heap.size() > 1) {
71+
const stone1 = heap.remove()
72+
const stone2 = heap.remove()
73+
74+
heap.insert(stone1 - stone2)
75+
}
76+
77+
return heap.peek()
78+
}

0 commit comments

Comments
 (0)