1 minute read

122. Best Time to Buy and Sell Stock II

문제 링크

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/

문제 설명

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.

제한 사항

  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4

입출력 예 #1

  1. Input : prices = [7,1,5,3,6,4]
  2. Output : 7
  3. Explanation : Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.

입출력 예 #2

  1. Input : prices = [1,2,3,4,5]
  2. Output : 4
  3. Explanation : Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.

입출력 예 #3

  1. Input : prices = [7,6,4,3,1]
  2. Output : 0
  3. Explanation : There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

문제 풀이

현재 가격보다 다음 가격이 높다면 그 차익의 합을 구하면 된다.

  1. 그리디 알고리즘
  2. 파이썬다운 방식
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
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # 0보다 크면 무조건 합산
        return sum(max(prices[i+1] - prices[i], 0) for i in range(len(prices) - 1))

Comments