[LeetCode] 121. Best Time to Buy an Sell Stock (Python)

유빈·2025년 2월 24일
0
post-thumbnail

Top Interview 150



121. Best Time to Buy and Sell Stock

Easy


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.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

 

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104



문제

  • 해당 문제에서는 한 번만 주식을 거래한다.
    • 즉, 누적합을 구하는 것이 아닌 딱 한 번의 사고팔기를 실행한다.
  • 인덱스 i가 날짜 개념으로 동작한다.
    • 인덱스 i일 때 주식을 구매했으면, 인덱스 i 이후의 날짜에 팔 수 있다.




Code

class Solution(object):
    def maxProfit(self, prices):
        max_profit = 0
        min_price = 999999999

        for i in range(len(prices)):
            min_price = min(min_price, prices[i])
            max_profit = max(max_profit, prices[i] - min_price)

        return max_profit
  • 반복문으로 prices를 순회하는 동안, min_price를 갱신해준다.
  • 각각의 날짜에 해당하는 가격에서 min_price를 뺀 값과 max_profit을 비교하여 max_profit을 갱신한다.
  • min_price는 최대 인덱스 i번의 가격이므로 prices[i]의 i보다 앞서지 않으므로 조건을 만족한다.





Time Complexity


O(N)O(N)


  • for i in range(len(prices)) : O(N)O(N)
  • min(), max() : O(N)O(N)





profile
🌱

0개의 댓글