|
2 | 2 | * @param {number[]} prices |
3 | 3 | * @return {number} |
4 | 4 | */ |
5 | | -var maxProfit = function(prices) { |
6 | | - |
7 | | - // NOTE: 해설 보고 쓴 코드입니다. |
8 | | - // i 번째 날에 prices[i]의 가격으로 주식을 팔아서 가장 큰 이익을 내려면 주식을 언제 샀어야 했을까? |
9 | | - // 정답은 바로 i 번째 날이 오기 전에 주식이 가장 쌌던 날 입니다! |
| 5 | +var maxProfit = function (prices) { |
10 | 6 |
|
11 | | - let maxProfit = 0; |
12 | 7 | let minPrice = prices[0]; |
| 8 | + let maxProfit = 0; |
| 9 | + |
| 10 | + for (let i = 1; i < prices.length; i++) { |
| 11 | + let currentPrice = prices[i]; |
13 | 12 |
|
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 | + } |
18 | 21 | } |
19 | 22 |
|
20 | 23 | return maxProfit; |
21 | | - |
22 | 24 | }; |
| 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