[Blind75] Best time to buy and sell stock

[Blind75]  Best time to buy and sell stock

problem

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

  • Input: prices = [7,1,5,3,6,4]
  • Output: 5
  • Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
    Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Python

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = prices[0]
        max_profit = 0

        for p in prices[1:]:
            max_profit = max(max_profit, p - min_price)
            min_price = min(min_price, p)

        return max_profit

처음에는 i,j 를 이용한 이중 for 문으로 brute force를 활용한 풀이를 했지만, 시간 초과가 아주 당연하게도 났다. 조건 중에 1 <= prices. Length <= 10^5로 아주 큰 크기의 input이 들어올 경우에는 시간 초과가 날 수밖에 없다.

위의 풀이는 O(n)의 시간복잡도를 가진다. 이중 for 문은 최악의 경우에는 거의 $n^2$의 시간복잡도를 가질 수도 있다는 함정이 존재한다. 위의 풀이는 한 번만 prices를 순회하기 때문에 O(n)의 시간복잡도를 가질 수 있다. 0에서 시작해서 뒤를 한 번 순회하면서 max_profit(target)를 초기화하고, min_price도 업데이트를 한다. 사실상 논리적으로는 이중 for문에서 하는 것과 비슷하지만, 한 번 만 돌 수 있도록 min, max를 사용한다는 것이 중요한 점으로 보인다.