파비의 매일매일 공부기록

2023.02.25 Today's Challenge 본문

Problem Solving/LeetCode

2023.02.25 Today's Challenge

fabichoi 2023. 2. 25. 23:45

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

 

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

n이 10^5라 O(n^2)은 TL 난다 =_=
알고 있었지만 시도 해봄. 역시나 TL

min_price와 max_profit 변수를 따로 둬서 풀면 되네..

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price, max_profit = float('inf'), 0
        for price in prices:
            if price < min_price:
                min_price = price
            else:
                max_profit = max(max_profit, price - min_price)
        return max_profit
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.02.27 Today's Challenge  (0) 2023.02.27
2023.02.26 Today's Challenge  (0) 2023.02.26
2023.02.24 Today's Challenge  (0) 2023.02.24
2023.02.23 Today's Challenge  (0) 2023.02.23
2023.02.22 Today's Challenge  (0) 2023.02.22
Comments