λ¬Έμ
νμ΄ κ³Όμ
νΉμ λ μ μ£Όμμ 맀λ νΉμ 맀μνμ¬ μ»μ μ μλ μ΅λ μ΄μ€μ κ³μ°νλ λμ κ³νλ²
λ¬Έμ μ
λλ€.
λ¬Έμ 쑰건μμ μ£Όμμ ꡬ맀 μ μλ ν맀λ₯Ό λ¨Όμ ν΄μΌνλ€λ κ²μ΄ λͺ
μλμ΄ μλ€λ μ μ μ μν©λλ€.
λ§μ½ dp(i, buy) = i λ²μ§Έ λ μ£Όμμ ν맀 μνκ° buy μΌ λ i μ΄ν μ»μ μ μλ μ΅λ μ΄μ€
μ΄λΌκ³ μ μνλ€λ©΄
λ€μκ³Ό κ°μ μ νμμ μ»μ μ μμ΅λλ€.
dp(i, buy) = max(dp(i+1, true) - stock[i], dp(i+1, false)), if buy == false
else(buy == true), dp(i, buy) = max(dp(i+2, false) + stock[i], dp(i+1, true))
μ¦, `i` λ²μ§Έ λ μ£Όμμ ꡬ맀ν μνλΌλ©΄ ν΄λΉ μ£Όμμ κ·Έλ ν맀νλ κ²κ³Ό ν맀νμ§ μκ³ λ€μ λ λ‘ λμ΄κ°λ κ²½μ°λ₯Ό λΉκ΅ν΄μ£Όκ³
λ°λλ‘ κ΅¬λ§€νμ§ μμ μνλΌλ©΄ `i` λ²μ§Έ λ ꡬ맀νκ±°λ ꡬ맀νμ§ μκ³ λμ΄κ°λ κ²μ κ³ λ €ν΄μ μ΅λ μ΄μ€μ ꡬν©λλ€.
μ½λ
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
const memo = new Array(prices.length)
.fill(0)
.map((_) => new Array(2).fill(-1));
function dp(i, buy) {
if (i >= prices.length) return 0;
if (memo[i][buy] !== -1) return memo[i][buy];
if (!buy) memo[i][buy] = Math.max(dp(i + 1, 1) - prices[i], dp(i + 1, 0));
else memo[i][buy] = Math.max(dp(i + 2, 0) + prices[i], dp(i + 1, 1));
return memo[i][buy];
}
const answer = dp(0, 0);
return answer;
};
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 881 - Boats to Save People (Medium) (0) | 2021.03.04 |
---|---|
LeetCode 234 - Palindrome Linked List (Easy) (0) | 2021.03.04 |
LeetCode 75 - Sort Colors (Medium) (0) | 2021.03.04 |
LeetCode 416 - Partition Equal Subset Sum (Medium) (0) | 2021.03.04 |
LeetCode 560 - Subarray Sum Equals K (Medium) (2) | 2021.03.04 |
π¬ λκΈ