-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0121_best_time_to_buy_and_sell_stock.html
More file actions
424 lines (355 loc) · 15.6 KB
/
Copy path0121_best_time_to_buy_and_sell_stock.html
File metadata and controls
424 lines (355 loc) · 15.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 121: Best Time to Buy and Sell Stock - Algorithm Visualization</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">#121</span> Best Time to Buy and Sell Stock</h1>
<p>Given an array prices where prices[i] is the price of a stock on day i, find the maximum profit from one transaction (buy then sell).</p>
<div class="problem-meta">
<span class="meta-tag">📁 Array</span>
<span class="meta-tag">🪟 Sliding Window</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(1)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0121_best_time_to_buy_and_sell_stock/0121_best_time_to_buy_and_sell_stock.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Imagine you're traveling through time, seeing stock prices each day:</p>
<ul>
<li><strong>Track minimum:</strong> Always remember the lowest price you've seen so far</li>
<li><strong>Calculate profit:</strong> At each day, calculate: "If I bought at the lowest and sold today, what's my profit?"</li>
<li><strong>Track maximum profit:</strong> Keep updating the best profit you could have made</li>
<li><strong>Why it works:</strong> For any selling day, the best buying day is always the minimum price before it</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="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Current Day</div>
<div class="variable-value" id="currentDay">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Min Price (Buy)</div>
<div class="variable-value" id="minPrice" style="color: #4caf50;">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Current Profit</div>
<div class="variable-value" id="currentProfit">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Max Profit</div>
<div class="variable-value" id="maxProfit" style="color: #2196f3;">0</div>
</div>
</div>
<div class="svg-container">
<svg id="visualization" width="700" height="300"></svg>
</div>
<div class="array-section">
<div class="array-label">📊 Price Array:</div>
<div class="array-container" id="priceContainer"></div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Best Time to Buy and Sell Stock
Problem from LeetCode: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Description:
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
"""
class Solution:
def max_profit(self, prices: List[int]) -> int:
"""
Find the maximum profit from buying and selling a stock.
Args:
prices: Array of stock prices
Returns:
int: Maximum profit possible
"""
if not prices or len(prices) < 2:
return 0
max_profit = 0
min_price = prices[0]
for price in prices:
# Update the minimum price seen so far
min_price = min(min_price, price)
# Calculate potential profit with current price
current_profit = price - min_price
# Update maximum profit if current profit is higher
max_profit = max(max_profit, current_profit)
return max_profit
def max_profit_brute_force(self, prices: List[int]) -> int:
"""
Brute force approach (inefficient, for illustration only).
Args:
prices: Array of stock prices
Returns:
int: Maximum profit possible
"""
max_profit = 0
n = len(prices)
for i in range(n):
for j in range(i + 1, n):
profit = prices[j] - prices[i]
max_profit = max(max_profit, profit)
return max_profit
def max_profit_dp(self, prices: List[int]) -> int:
"""
Dynamic programming approach.
Args:
prices: Array of stock prices
Returns:
int: Maximum profit possible
"""
if not prices or len(prices) < 2:
return 0
n = len(prices)
# dp[i] represents the maximum profit up to day i
dp = [0] * n
min_price = prices[0]
for i in range(1, n):
# Calculate profit if selling on day i
dp[i] = max(dp[i-1], prices[i] - min_price)
# Update minimum price
min_price = min(min_price, prices[i])
return dp[n-1]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
prices1 = [7, 1, 5, 3, 6, 4]
result1 = solution.max_profit(prices1)
print(f"Example 1: prices={prices1}")
print(f"Maximum profit: {result1}") # Expected output: 5
# Example 2
prices2 = [7, 6, 4, 3, 1]
result2 = solution.max_profit(prices2)
print(f"\nExample 2: prices={prices2}")
print(f"Maximum profit: {result2}") # Expected output: 0
# Additional example
prices3 = [2, 4, 1]
result3 = solution.max_profit(prices3)
print(f"\nExample 3: prices={prices3}")
print(f"Maximum profit: {result3}") # Expected output: 2
# Compare approaches (using a small array for brute force)
small_prices = [7, 1, 5, 3, 6]
print("\nComparing approaches:")
print(f"Optimal approach: {solution.max_profit(small_prices)}")
print(f"Brute force approach: {solution.max_profit_brute_force(small_prices)}")
print(f"DP approach: {solution.max_profit_dp(small_prices)}")
</pre>
</div>
</div>
</div>
<script>
const prices = [7, 1, 5, 3, 6, 4];
let currentIndex = 0;
let minPrice = Infinity;
let maxProfit = 0;
let minPriceIndex = -1;
let bestBuyIndex = -1;
let bestSellIndex = -1;
let autoInterval = null;
const svg = d3.select("#visualization");
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const width = 700 - margin.left - margin.right;
const height = 250 - margin.top - margin.bottom;
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const xScale = d3.scaleLinear()
.domain([0, prices.length - 1])
.range([0, width]);
const yScale = d3.scaleLinear()
.domain([0, Math.max(...prices) + 1])
.range([height, 0]);
// Draw line chart
const line = d3.line()
.x((d, i) => xScale(i))
.y(d => yScale(d));
g.append("path")
.datum(prices)
.attr("fill", "none")
.attr("stroke", "#667eea")
.attr("stroke-width", 3)
.attr("d", line);
// Add axes
g.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale).ticks(prices.length - 1).tickFormat(d => `Day ${d}`));
g.append("g")
.call(d3.axisLeft(yScale).tickFormat(d => `$${d}`));
function init() {
renderPrices();
renderChart();
}
function renderPrices() {
const container = document.getElementById('priceContainer');
container.innerHTML = '';
prices.forEach((price, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `price-${idx}`;
box.innerHTML = `$${price}<span class="index-label">Day ${idx}</span>`;
if (idx === minPriceIndex) {
box.style.background = '#c8e6c9';
box.style.borderColor = '#4caf50';
}
if (idx === currentIndex && currentIndex < prices.length) {
box.classList.add('highlight');
}
if (idx === bestSellIndex && maxProfit > 0) {
box.style.background = '#bbdefb';
box.style.borderColor = '#2196f3';
}
container.appendChild(box);
});
}
function renderChart() {
// Remove old markers
g.selectAll(".marker").remove();
g.selectAll(".profit-line").remove();
// Draw points
g.selectAll(".marker")
.data(prices.slice(0, currentIndex + 1))
.enter()
.append("circle")
.attr("class", "marker")
.attr("cx", (d, i) => xScale(i))
.attr("cy", d => yScale(d))
.attr("r", (d, i) => i === currentIndex ? 8 : 5)
.attr("fill", (d, i) => {
if (i === minPriceIndex) return "#4caf50";
if (i === currentIndex) return "#ff9800";
return "#667eea";
})
.attr("stroke", "#fff")
.attr("stroke-width", 2);
// Draw profit line if we have a min price
if (minPriceIndex >= 0 && currentIndex > minPriceIndex) {
g.append("line")
.attr("class", "profit-line")
.attr("x1", xScale(minPriceIndex))
.attr("y1", yScale(prices[minPriceIndex]))
.attr("x2", xScale(currentIndex))
.attr("y2", yScale(prices[currentIndex]))
.attr("stroke", "#4caf50")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5");
}
}
function step() {
if (currentIndex >= prices.length) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Done! Maximum profit = $${maxProfit} (Buy day ${bestBuyIndex} at $${prices[bestBuyIndex]}, Sell day ${bestSellIndex} at $${prices[bestSellIndex]})`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const price = prices[currentIndex];
// Update min price
if (price < minPrice) {
minPrice = price;
minPriceIndex = currentIndex;
document.getElementById('statusMessage').textContent =
`Day ${currentIndex}: Price $${price} is new minimum! Updated min_price.`;
}
// Calculate current profit
const currentProfit = price - minPrice;
document.getElementById('currentProfit').textContent = `$${currentProfit}`;
// Update max profit
if (currentProfit > maxProfit) {
maxProfit = currentProfit;
bestBuyIndex = minPriceIndex;
bestSellIndex = currentIndex;
document.getElementById('statusMessage').textContent =
`Day ${currentIndex}: New max profit! Buy at $${minPrice} (day ${minPriceIndex}), sell at $${price} = $${currentProfit}`;
} else if (price >= minPrice) {
document.getElementById('statusMessage').textContent =
`Day ${currentIndex}: Price $${price}. Profit if sold = $${currentProfit}. Max profit still $${maxProfit}.`;
}
document.getElementById('currentDay').textContent = currentIndex;
document.getElementById('minPrice').textContent = `$${minPrice}`;
document.getElementById('maxProfit').textContent = `$${maxProfit}`;
renderPrices();
renderChart();
currentIndex++;
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (currentIndex >= prices.length) {
step();
stopAuto();
} else {
step();
}
}, 1000);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
currentIndex = 0;
minPrice = Infinity;
maxProfit = 0;
minPriceIndex = -1;
bestBuyIndex = -1;
bestSellIndex = -1;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
document.getElementById('currentDay').textContent = '0';
document.getElementById('minPrice').textContent = '-';
document.getElementById('currentProfit').textContent = '0';
document.getElementById('maxProfit').textContent = '0';
// Clear chart markers
g.selectAll(".marker").remove();
g.selectAll(".profit-line").remove();
init();
}
init();
</script>
</body>
</html>