-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1046_last_stone_weight.html
More file actions
465 lines (394 loc) · 16.5 KB
/
Copy path1046_last_stone_weight.html
File metadata and controls
465 lines (394 loc) · 16.5 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Last Stone Weight - LeetCode 1046</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#1046</span> Last Stone Weight</h1>
<p><strong>Problem:</strong> Smash the two heaviest stones together. If unequal, the lighter is destroyed and the heavier loses that weight. Return last stone weight (or 0).</p>
<p><strong>Pattern:</strong> Max Heap - Always pick two largest stones efficiently</p>
<div class="problem-meta">
<span class="meta-tag">📝 Algorithm</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/1046_last_stone_weight/1046_last_stone_weight.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="800">
</div>
</div>
<div class="status" id="status">Click "Step" to smash stones</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Heap (Max):</span>
<span id="heapDisplay">[7, 4, 2, 1, 8, 1]</span>
</div>
<div class="var-item">
<span class="var-label">Smashing:</span>
<span id="smashDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Result:</span>
<span id="resultDisplay">-</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>import heapq
"""
LeetCode Last Stone Weight
Problem from LeetCode: https://leetcode.com/problems/last-stone-weight/
You are given an array of integers stones where stones[i] is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together.
Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:
- If x == y, both stones are destroyed, and
- If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.
Example 1:
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
Example 2:
Input: stones = [1]
Output: 1
Constraints:
- 1 <= stones.length <= 30
- 1 <= stones[i] <= 1000
"""
class Solution:
def last_stone_weight(self, stones):
stones = [(-s) for s in stones]
heapq.heapify(stones)
while len(stones) > 1:
y = -heapq.heappop(stones)
x = -heapq.heappop(stones)
if x != y:
heapq.heappush(stones, -(y - x))
return -stones[0] if stones else 0
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
stones = [2,7,4,1,8,1]
result = solution.last_stone_weight(stones)
print(f"Example 1: {result}") # Expected: 1
# Example 2
stones = [1]
result = solution.last_stone_weight(stones)
print(f"Example 2: {result}") # Expected: 1
</pre>
</div>
</div>
</div>
<script>
const initialStones = [2, 7, 4, 1, 8, 1];
let heap = [];
let phase = 'init'; // 'init' | 'pick' | 'smash' | 'done'
let stone1 = null, stone2 = null;
let smashHistory = [];
let autoRunning = false;
let autoTimer = null;
const width = 700;
const height = 420;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
// Max heap operations
function heapPush(val) {
heap.push(val);
let i = heap.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (heap[parent] >= heap[i]) break;
[heap[parent], heap[i]] = [heap[i], heap[parent]];
i = parent;
}
}
function heapPop() {
if (heap.length === 0) return null;
const max = heap[0];
heap[0] = heap[heap.length - 1];
heap.pop();
let i = 0;
while (true) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let largest = i;
if (left < heap.length && heap[left] > heap[largest]) largest = left;
if (right < heap.length && heap[right] > heap[largest]) largest = right;
if (largest === i) break;
[heap[i], heap[largest]] = [heap[largest], heap[i]];
i = largest;
}
return max;
}
function drawHeap() {
const startX = width / 2;
const startY = 80;
const levelHeight = 55;
function drawNode(idx, x, y, level) {
if (idx >= heap.length) return;
const nodeRadius = 25;
const spread = 120 / (level + 1);
// Draw edges first
const leftIdx = 2 * idx + 1;
const rightIdx = 2 * idx + 2;
if (leftIdx < heap.length) {
svg.append("line")
.attr("x1", x).attr("y1", y + nodeRadius)
.attr("x2", x - spread).attr("y2", y + levelHeight - nodeRadius)
.attr("stroke", "#ddd").attr("stroke-width", 2);
drawNode(leftIdx, x - spread, y + levelHeight, level + 1);
}
if (rightIdx < heap.length) {
svg.append("line")
.attr("x1", x).attr("y1", y + nodeRadius)
.attr("x2", x + spread).attr("y2", y + levelHeight - nodeRadius)
.attr("stroke", "#ddd").attr("stroke-width", 2);
drawNode(rightIdx, x + spread, y + levelHeight, level + 1);
}
// Draw node
const isTop = idx === 0;
const isSecond = idx === 1 || idx === 2;
svg.append("circle")
.attr("cx", x).attr("cy", y).attr("r", nodeRadius)
.attr("fill", isTop ? "#bbdefb" : isSecond ? "#e3f2fd" : "#f5f5f5")
.attr("stroke", isTop ? "#1565c0" : "#1976d2")
.attr("stroke-width", isTop ? 3 : 2);
svg.append("text")
.attr("x", x).attr("y", y + 7)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(heap[idx]);
}
if (heap.length > 0) {
drawNode(0, startX, startY, 0);
}
}
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2).attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Last Stone Weight (Max Heap)");
// Draw heap
svg.append("text")
.attr("x", 50).attr("y", 55)
.attr("font-size", "12px")
.text("Max Heap:");
if (heap.length > 0) {
drawHeap();
} else {
svg.append("text")
.attr("x", width / 2).attr("y", 120)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("fill", "#999")
.text("(empty)");
}
// Smash visualization
if (stone1 !== null && stone2 !== null) {
svg.append("rect")
.attr("x", 50).attr("y", 280)
.attr("width", 300).attr("height", 80)
.attr("rx", 10)
.attr("fill", "#fff3e0").attr("stroke", "#ff9800");
// Stone 1
svg.append("circle")
.attr("cx", 100).attr("cy", 320)
.attr("r", 30)
.attr("fill", "#ffeb3b").attr("stroke", "#f57c00");
svg.append("text")
.attr("x", 100).attr("y", 327)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.text(stone1);
// VS
svg.append("text")
.attr("x", 175).attr("y", 327)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.attr("fill", "#e53935")
.text("💥");
// Stone 2
svg.append("circle")
.attr("cx", 250).attr("cy", 320)
.attr("r", 30)
.attr("fill", "#ffeb3b").attr("stroke", "#f57c00");
svg.append("text")
.attr("x", 250).attr("y", 327)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.text(stone2);
// Result
if (phase === 'smash') {
const diff = stone1 - stone2;
svg.append("text")
.attr("x", 320).attr("y", 327)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.text(`= ${diff}`);
}
}
// History
svg.append("text")
.attr("x", 400).attr("y", 290)
.attr("font-weight", "bold")
.text("History:");
smashHistory.slice(-4).forEach((entry, i) => {
svg.append("text")
.attr("x", 400).attr("y", 310 + i * 20)
.attr("font-size", "12px")
.text(entry);
});
// Result
if (phase === 'done') {
const result = heap.length > 0 ? heap[0] : 0;
svg.append("rect")
.attr("x", width / 2 - 80).attr("y", height - 60)
.attr("width", 160).attr("height", 45)
.attr("rx", 10)
.attr("fill", "#c8e6c9").attr("stroke", "#4caf50");
svg.append("text")
.attr("x", width / 2).attr("y", height - 30)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(`Result: ${result}`);
}
}
function step() {
if (phase === 'init') {
heap = [];
initialStones.forEach(s => heapPush(s));
phase = 'pick';
document.getElementById("heapDisplay").textContent =
`[${heap.join(', ')}]`;
document.getElementById("status").textContent =
"Built max heap. Ready to smash!";
draw();
return true;
}
if (phase === 'pick') {
if (heap.length <= 1) {
phase = 'done';
const result = heap.length > 0 ? heap[0] : 0;
document.getElementById("resultDisplay").textContent = result;
document.getElementById("status").textContent =
`Done! Last stone weight: ${result}`;
draw();
return false;
}
stone1 = heapPop();
stone2 = heapPop();
document.getElementById("smashDisplay").textContent =
`${stone1} vs ${stone2}`;
document.getElementById("status").textContent =
`Pick two heaviest: ${stone1} and ${stone2}`;
phase = 'smash';
draw();
return true;
}
if (phase === 'smash') {
const diff = stone1 - stone2;
smashHistory.push(`${stone1} - ${stone2} = ${diff}`);
if (diff > 0) {
heapPush(diff);
document.getElementById("status").textContent =
`${stone1} > ${stone2}: ${diff} remains, pushed to heap`;
} else {
document.getElementById("status").textContent =
`${stone1} = ${stone2}: Both destroyed!`;
}
document.getElementById("heapDisplay").textContent =
heap.length > 0 ? `[${heap.join(', ')}]` : "[]";
stone1 = null;
stone2 = null;
phase = 'pick';
draw();
return true;
}
return false;
}
function reset() {
heap = [];
phase = 'init';
stone1 = null;
stone2 = null;
smashHistory = [];
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("heapDisplay").textContent =
`[${initialStones.join(', ')}]`;
document.getElementById("smashDisplay").textContent = "-";
document.getElementById("resultDisplay").textContent = "-";
document.getElementById("status").textContent =
'Click "Step" to smash stones';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
</body>
</html>