알고리즘
그리디 알고리즘 예제
jwjwvison
2022. 5. 19. 21:15
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/submissions/
Best Time to Buy and Sell Stock II - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
내리기 전에 팔고, 오르기 전에 사면 된다. 이 문제에서는 다음번의 등락 여부를 미리 알 수 있기 때문에 몇 번이든 거래가 가능하다.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
result=0
# 값이 오르는 경우 매번 그리디 계산
for i in range(len(prices)-1):
if prices[i+1] > prices[i]:
result += prices[i+1] - prices[i]
return result