본문 바로가기

problem solving/leetcode

leetcode/python/ 121. Best Time to Buy and Sell Stock

Description

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? 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 choosin

leetcode.com

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.

 


Process

Constraints:

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

처음엔 stack을 쓸까 했는데 문제를 찬찬히 읽어보니 그냥 단순 비교 연산만으로 쉽게 풀리는 문제였다.

 

 


Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        min_price = prices[0]
        for i in range(1, len(prices)):
            if min_price > prices[i]:
                min_price = prices[i]
            else:
                profit = max(profit, prices[i]-min_price)
        return profit

profit을 0으로 초기화, 리스트의 처음 값을 최소값으로 지정해주고 다음 요소부터 리스트를 순회하면서 해당 요소 값을 비교해 최대 profit을 구하도록 구현했다.

 


Conclusion

min, max 연산과 if문 사용으로 처리하는 것의 효율성 차이가 궁금하다...... gpt한테도 물어보고 구글링도 해봤는데 확신을 못 얻었다.