-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0875_koko_eating_bananas.html
More file actions
365 lines (309 loc) Β· 13.7 KB
/
Copy path0875_koko_eating_bananas.html
File metadata and controls
365 lines (309 loc) Β· 13.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Koko Eating Bananas - LeetCode 875</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">#875</span> Koko Eating Bananas π</h1>
<p>Koko wants to eat all bananas before guards return. Find the minimum eating speed. Binary search on the answer!</p>
<div class="problem-meta">
<span class="meta-tag">π Binary Search</span>
<span class="meta-tag">π’ Array</span>
<span class="meta-tag">β±οΈ O(n log m)</span>
</div>
<div class="file-ref">
π Python: <a href="../python/0875_koko_eating_bananas/0875_koko_eating_bananas.py">0875_koko_eating_bananas.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>π‘ How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Problem:</strong> Koko needs to eat all bananas before guards return in h hours</li>
<li><strong>Each hour:</strong> She picks one pile and eats k bananas (or all if less than k)</li>
<li><strong>Goal:</strong> Find minimum speed k that lets her finish in time</li>
<li><strong>Binary search on speed:</strong> Speed can be 1 to max(piles)</li>
<li><strong>For each pile:</strong> Hours = ceil(pile / speed)</li>
<li><strong>If total hours β€ h:</strong> Speed is fast enough, try slower</li>
<li><strong>If total hours > h:</strong> Too slow, need faster speed</li>
</ul>
</div>
<div class="visualization-section">
<h3>π¬ Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="info-box">
β° Guards return in h = 8 hours
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to find Koko's minimum eating speed
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Speed Range</div>
<div class="variable-value" id="rangeVal">1 - 11</div>
</div>
<div class="variable-box">
<div class="variable-name">Test Speed (k)</div>
<div class="variable-value" id="speedVal">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Hours Needed</div>
<div class="variable-value" id="hoursVal">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Can Finish?</div>
<div class="variable-value" id="canFinishVal">-</div>
</div>
</div>
<div class="array-section">
<div class="array-label">Banana Piles:</div>
<div class="array-container" id="pilesContainer"></div>
</div>
<div class="array-section">
<div class="array-label">Hours per pile at current speed:</div>
<div class="array-container" id="hoursContainer"></div>
</div>
<div class="info-box" id="resultBox" style="display: none;"></div>
</div>
<div class="code-section">
<h3>π» Python Solution</h3>
<div class="code-block">
<pre>from typing import List
import math
"""
LeetCode Koko Eating Bananas
Problem from LeetCode: https://leetcode.com/problems/koko-eating-bananas/
Description:
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Example 1:
Input: piles = [3,6,7,11], h = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], h = 6
Output: 23
Constraints:
1 <= piles.length <= 10^4
piles.length <= h <= 10^9
1 <= piles[i] <= 10^9
"""
class Solution:
def min_eating_speed(self, piles: List[int], h: int) ->int:
"""
Find the minimum eating speed k such that Koko can eat all the bananas within h hours.
Args:
piles: List of banana piles where piles[i] represents the number of bananas in the ith pile
h: The maximum number of hours Koko can take to eat all bananas
Returns:
int: The minimum integer k such that Koko can eat all the bananas within h hours
"""
left = 1
right = max(piles)
while left < right:
mid = (left + right) // 2
if self._can_finish(piles, mid, h):
right = mid
else:
left = mid + 1
return left
def _can_finish(self, piles: List[int], speed: int, h: int) ->bool:
"""
Check if Koko can eat all bananas within h hours at the given speed.
Args:
piles: List of banana piles
speed: Eating speed (bananas per hour)
h: Maximum hours allowed
Returns:
bool: True if Koko can finish all bananas within h hours, False otherwise
"""
hours = 0
for pile in piles:
hours += math.ceil(pile / speed)
if hours > h:
return False
return True
def minEatingSpeed_alt(self, piles: List[int], h: int) ->int:
"""
Alternative implementation with a different binary search approach.
Args:
piles: List of banana piles
h: Maximum hours allowed
Returns:
int: The minimum eating speed required
"""
left = 1
right = max(piles)
result = right
while left <= right:
mid = (left + right) // 2
hours = sum(math.ceil(pile / mid) for pile in piles)
if hours <= h:
result = min(result, mid)
right = mid - 1
else:
left = mid + 1
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
piles1 = [3, 6, 7, 11]
h1 = 8
result1 = solution.min_eating_speed(piles1, h1)
print(f"Example 1: {result1}") # Expected: 4
# Example 2
piles2 = [30, 11, 23, 4, 20]
h2 = 5
result2 = solution.min_eating_speed(piles2, h2)
print(f"Example 2: {result2}") # Expected: 30
# Example 3
piles3 = [30, 11, 23, 4, 20]
h3 = 6
result3 = solution.min_eating_speed(piles3, h3)
print(f"Example 3: {result3}") # Expected: 23
</pre>
</div>
</div>
</div>
<script>
const piles = [3, 6, 7, 11];
const h = 8;
let left = 1;
let right = Math.max(...piles);
let currentSpeed = -1;
let phase = 'init';
let autoInterval = null;
function init() {
left = 1;
right = Math.max(...piles);
currentSpeed = -1;
renderPiles();
document.getElementById('hoursContainer').innerHTML = '<span style="color: #999;">Select a speed to calculate...</span>';
document.getElementById('rangeVal').textContent = `${left} - ${right}`;
document.getElementById('speedVal').textContent = '-';
document.getElementById('hoursVal').textContent = '-';
document.getElementById('canFinishVal').textContent = '-';
document.getElementById('resultBox').style.display = 'none';
}
function renderPiles() {
const container = document.getElementById('pilesContainer');
container.innerHTML = '';
piles.forEach((pile, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.style.background = '#fff8e1';
box.style.borderColor = '#ffc107';
box.innerHTML = `π ${pile}<span class="index-label">pile ${idx + 1}</span>`;
container.appendChild(box);
});
}
function calculateHours(speed) {
return piles.map(pile => Math.ceil(pile / speed));
}
function renderHours(speed) {
const container = document.getElementById('hoursContainer');
container.innerHTML = '';
const hoursPerPile = calculateHours(speed);
hoursPerPile.forEach((hours, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.style.background = '#e3f2fd';
box.style.borderColor = '#2196f3';
box.innerHTML = `${hours}h<span class="index-label">β${piles[idx]}/${speed}β</span>`;
container.appendChild(box);
});
// Total
const total = hoursPerPile.reduce((a, b) => a + b, 0);
const totalBox = document.createElement('div');
totalBox.className = 'array-box';
totalBox.style.background = total <= h ? '#e8f5e9' : '#ffebee';
totalBox.style.borderColor = total <= h ? '#4caf50' : '#f44336';
totalBox.style.fontWeight = 'bold';
totalBox.innerHTML = `= ${total}h<span class="index-label">total</span>`;
container.appendChild(totalBox);
}
function step() {
if (phase === 'init') {
phase = 'searching';
document.getElementById('statusMessage').textContent =
'Binary search for minimum speed between 1 and max(piles)...';
}
if (phase === 'searching') {
if (left >= right) {
phase = 'done';
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box secondary';
document.getElementById('resultBox').textContent = `β
Minimum speed: ${left} bananas/hour`;
document.getElementById('statusMessage').textContent =
`Found! Koko needs to eat at least ${left} bananas per hour to finish in ${h} hours.`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
currentSpeed = Math.floor((left + right) / 2);
const hoursNeeded = calculateHours(currentSpeed).reduce((a, b) => a + b, 0);
const canFinish = hoursNeeded <= h;
document.getElementById('rangeVal').textContent = `${left} - ${right}`;
document.getElementById('speedVal').textContent = currentSpeed;
document.getElementById('hoursVal').textContent = `${hoursNeeded} / ${h}`;
document.getElementById('canFinishVal').textContent = canFinish ? 'β
Yes' : 'β No';
document.getElementById('canFinishVal').style.color = canFinish ? '#4caf50' : '#f44336';
renderHours(currentSpeed);
if (canFinish) {
document.getElementById('statusMessage').textContent =
`Speed ${currentSpeed}: ${hoursNeeded} hours β€ ${h} hours β Try slower! right = ${currentSpeed}`;
right = currentSpeed;
} else {
document.getElementById('statusMessage').textContent =
`Speed ${currentSpeed}: ${hoursNeeded} hours > ${h} hours β Too slow! left = ${currentSpeed + 1}`;
left = currentSpeed + 1;
}
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1500);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to find Koko\'s minimum eating speed';
init();
}
init();
</script>
</body>
</html>