Problem Solving/LeetCode
Today's Challenge
fabichoi
2022. 12. 23. 23:45
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
Best Time to Buy and Sell Stock with Cooldown - LeetCode
Best Time to Buy and Sell Stock with Cooldown - You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell o
leetcode.com
DP 문제.
뒤에서 부터 풀어야 되나 했는데, 단순 점화식으로도 풀리는 문제인 듯
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
prev_sell, sell, buy = 0, 0, -prices[0]
for i in range(1, len(prices)):
prev_sell, sell, buy = sell, max(buy+prices[i], sell), max(prev_sell-prices[i], buy)
return max(sell, buy)
반응형