You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1
예시 1
(prices = [7,1,5,3,6,4]): 최대 이익은 7입니다.
2일째에 1에 구매하여 3일째에 5에 판매 (이익 = 4), 그리고 4일째에 3에 구매하여 5일째에 6에 판매 (이익 = 3).
총 이익 = 4 + 3 = 7.
Example 2
예시 2
(prices = [1,2,3,4,5]): 최대 이익은 4입니다.
1일째에 1에 구매하여 5일째에 5에 판매 (이익 = 4).
총 이익 = 4.
121번 문제
최적의 구매일과 판매일 찾아서 한번의 거래로 최대 이익을 실현
122번 문제
매일 주식읠 가격의 변동을 활용하여 여러 번의 거래로 최대 이익을 실현
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
# 비슷하지만 다름
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
# 다음 숫자보다 크다면 max_profit 변경해줌
max_profit += prices[i] - prices[i - 1]
# 변경해주면서 동시에 더해줌
return max_profit