122. Best Time to Buy and Sell Stock II ★★★★★
122. Best Time to Buy and Sell Stock II
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
👉 prices[i]는 i번째 날의 주가를 나타내는 정수 배열 prices가 주어집니다.
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.
👉 항상 최대 1주까지만 보유할 수 있습니다.
즉, 이미 주식을 갖고 있다면 새로 살 수 없습니다.
However, you can buy it then immediately sell it on the same day.
👉 단, 같은 날에 사고 바로 파는 것도 허용됩니다.
Find and return the maximum profit you can achieve.
👉 이렇게 사고팔기를 했을 때 얻을 수 있는 최대 이익을 구해서 반환하세요.
✅ 요약
- 원하는 만큼 사고팔기 가능 (단, 한 번에 한 주만 보유 가능)
- 같은 날 사고 팔 수 있음
- 최대 수익을 구하라
https://youtu.be/3SJ3pUkPQMc?si=lGgpC5TAjAvrsyYM
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
# 상승 구간에서만 매수-매도
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profit
그런데, prices[i] > prices[i-1] 보면, 하루 건너서만 이익 계산을 할수 있어. 어떻게 생각해?
결론
prices[i] > prices[i-1] 방식은 하루 건너 매매처럼 보이지만, 실제로는 모든 상승 구간을 적절히 처리하며, 최종 결과는 누적 상승과 동일합니다. 이 방식은 효율적이고, 문제 조건을 만족하는 적합한 접근법입니다.