https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
prices = [3, 2, 1, 4]
prices = [7, 1, 5, 3, 6, 4]
prices = [1, 3, 0, 1, 3, 0]
def sol(prices):
answer = 0
for i = 1...prices.len:
이익 = 판매 가격[i] - 구매 가격[i - 1]
if 이익 > 0:
answer += 이익
return answer
class Solution:
def maxProfit(self, prices: List[int]) -> int:
answer = 0
for i in range(1, len(prices)):
profit = prices[i] - prices[i - 1]
answer += profit if profit > 0 else 0
return answer
그리디 유형의 문제였다. 즉, 현재 가장 최선의 방법을 택해야 한다. 따라서 싸게 구매해서 다음날 이익이 나면 판매하는 방식으로 구현하였다.