Skip to content

Commit bdeaaaf

Browse files
committed
best time to buy and sell stock solution
1 parent 54df655 commit bdeaaaf

File tree

1 file changed

+39
-11
lines changed

1 file changed

+39
-11
lines changed

β€Žbest-time-to-buy-and-sell-stock/robinyoon-dev.jsβ€Ž

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,49 @@
22
* @param {number[]} prices
33
* @return {number}
44
*/
5-
var maxProfit = function(prices) {
6-
7-
// NOTE: ν•΄μ„€ 보고 μ“΄ μ½”λ“œμž…λ‹ˆλ‹€.
8-
// i 번째 날에 prices[i]의 κ°€κ²©μœΌλ‘œ 주식을 νŒ”μ•„μ„œ κ°€μž₯ 큰 이읡을 λ‚΄λ €λ©΄ 주식을 μ–Έμ œ 샀어야 ν–ˆμ„κΉŒ?
9-
// 정닡은 λ°”λ‘œ i 번째 날이 였기 전에 주식이 κ°€μž₯ 쌌던 λ‚  μž…λ‹ˆλ‹€!
5+
var maxProfit = function (prices) {
106

11-
let maxProfit = 0;
127
let minPrice = prices[0];
8+
let maxProfit = 0;
9+
10+
for (let i = 1; i < prices.length; i++) {
11+
let currentPrice = prices[i];
1312

14-
for(const price of prices){
15-
const profit = price - minPrice
16-
maxProfit = Math.max(maxProfit, profit);
17-
minPrice = Math.min(price, minPrice);
13+
if (currentPrice < minPrice) {
14+
minPrice = currentPrice;
15+
} else{
16+
let profit = currentPrice - minPrice;
17+
if(profit > maxProfit){
18+
maxProfit = profit;
19+
}
20+
}
1821
}
1922

2023
return maxProfit;
21-
2224
};
25+
26+
27+
// -----μ•„λž˜λŠ” 이전에 μž‘μ„±ν•œ λ‹΅μ•ˆμž…λ‹ˆλ‹€.
28+
// /**
29+
// * @param {number[]} prices
30+
// * @return {number}
31+
// */
32+
// var maxProfit = function(prices) {
33+
34+
// // NOTE: ν•΄μ„€ 보고 μ“΄ μ½”λ“œμž…λ‹ˆλ‹€.
35+
// // i 번째 날에 prices[i]의 κ°€κ²©μœΌλ‘œ 주식을 νŒ”μ•„μ„œ κ°€μž₯ 큰 이읡을 λ‚΄λ €λ©΄ 주식을 μ–Έμ œ 샀어야 ν–ˆμ„κΉŒ?
36+
// // 정닡은 λ°”λ‘œ i 번째 날이 였기 전에 주식이 κ°€μž₯ 쌌던 λ‚  μž…λ‹ˆλ‹€!
37+
38+
// let maxProfit = 0;
39+
// let minPrice = prices[0];
40+
41+
// for(const price of prices){
42+
// const profit = price - minPrice
43+
// maxProfit = Math.max(maxProfit, profit);
44+
// minPrice = Math.min(price, minPrice);
45+
// }
46+
47+
// return maxProfit;
48+
49+
// };
50+

0 commit comments

Comments
Β (0)