|
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