-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
λ¬Έμ μ€λͺ | Best Time to Buy and Sell Stock II
μ£Όμμ λ§€μΌ κ±°λν μ μμΌλ©°, μ΅λ ν μ£Όλ§ λ³΄μ ν μ μμ λ μ»μ μ μλ μ΅λ μ΄μ΅μ ꡬνλ λ¬Έμ μ λλ€. κ°μ λ μ ꡬ맀νκ³ νλ§€νλ κ²λ κ°λ₯
π μ μ½μ‘°κ±΄
1 <= prices.length <= 3 * 10^40 <= prices[i] <= 10^4- ν λ²μ μ΅λ 1μ£Όλ§ λ³΄μ κ°λ₯
- κ°μ λ κ±°λ κ°λ₯
π‘ μμ
- Input:
[7,1,5,3,6,4]- Output:
7 - μ€λͺ
:
- 2μΌμ°¨ ꡬ맀(1), 3μΌμ°¨ νλ§€(5) β μ΄μ΅ 4
- 4μΌμ°¨ ꡬ맀(3), 5μΌμ°¨ νλ§€(6) β μ΄μ΅ 3
- μ΄ μ΄μ΅: 4 + 3 = 7
- Output:
λ¬Έμ ν΄κ²° κ³Όμ
Step 1: λ¬Έμ μ΄ν΄νκΈ°
- μμ μμλ‘ μ§μ νμ΄λ³΄κΈ°:
[1,2,3]β λ§€μΌ μ€λ₯΄λ 2μ μ΄μ΅[3,2,1]β κ³μ νλ½νλ 0μ μ΄μ΅[1,2,1,3]β 1β2 (μ΄μ΅1) + 1β3 (μ΄μ΅2) = μ΄ μ΄μ΅ 3
Step 2: μ κ·Ό λ°©λ²
-
μ§κ΄μ μΌλ‘ μκ°νκΈ°
- λ§€μΌλ§€μΌμ κ°κ²© λ³λμ νμΈ
- μμΉνλ ꡬκ°μμλ νμ μ΄μ΅ μ€ν κ°λ₯
- νλ½νλ ꡬκ°μμλ κ±°λνμ§ μμ
-
μκ³ λ¦¬μ¦ ν μμ±
i = 1 (첫째λ λΆν° μμ)
β
μ€λ κ°κ²©(prices[i])κ³Ό μ΄μ κ°κ²©(prices[i-1]) λΉκ΅
β
μ€λ κ°κ²©μ΄ λ λλ€λ©΄
β μ΄μ΅(profit)μ μ°¨μ΅ λνκΈ°
β
i++ νκ³ λ€μ μ²μμΌλ‘
Step 3: μ½λ μ€κ³
- μ΄ μ΄μ΅(profit) λ³μ μ΄κΈ°ν
- λμ§Έλ (i=1)λΆν° λ§μ§λ§λ κΉμ§ μν:
- λΉμΌ κ°κ²©μ΄ μ μΌ κ°κ²©λ³΄λ€ λμΌλ©΄
- μ°¨μ΅μ μ΄ μ΄μ΅μ λν¨
- μ΅μ’ μ΄μ΅ λ°ν
Step 4: μ½λ ꡬν
var maxProfit = function(prices) {
let profit = 0
for(let i = 1; i < prices.length; i++) {
if(prices[i] - prices[i - 1] > 0) {
profit += prices[i] - prices[i - 1]
}
}
return profit
};