[Problem Solving with Python] LeetCode 121. Best Time to Buy and Sell Stock

Seokgi Kim·2021년 10월 13일
0

문제

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

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.

Test Case Example:

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.

풀이

Solution 1.

def maxProfit(self, prices: List[int]) -> int:
    max_profit = 0
    for i in range(len(prices)):
        if i == 0:
            min_price = prices[i]
        elif prices[i] < min_price:
            min_price = prices[i]
        elif prices[i] - min_price > max_profit:
            max_profit = prices[i] - min_price
   return max_profit

한 번 순회하는 동안 현재까지 지나온 지점 중 최소 지점을 저장하고, 현재 위치의 가격 - 최소 가격이 현재까지 중의 가장 큰 이익보다 크면 이를 가장 큰 이익에 저장하는 방식의 풀이이다.

Time Complexity: 한 번 순회하므로 O(n)
Space Complexity: O(1)

Full Code

Link: https://github.com/datawhales/Python-Code-Notes/blob/main/ps/leet_121_best-time-to-buy-and-sell-stock_211012.py

profile
Data Scientist, NLP/ML Engineer

0개의 댓글