Search

[121] Best Time to By and Sell Stock

태그
DFS
Tier
날짜
2025/03/14

Question

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.
Plain Text
복사
Example 2:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.
Plain Text
복사

My Answer

# Time Limit Exceeded class Solution: def maxProfit(self, prices: List[int]) -> int: max_profit = 0 for i in range(len(prices)): for j in range(i,len(prices)): max_profit = max(max_profit, prices[j]-prices[i]) return max_profit # Time Limit Exceeded class Solution: def maxProfit(self, prices: List[int]) -> int: max_profit = 0 for i in range(len(prices)): local_max = max(prices[i:]) - prices[i] max_profit = max(max_profit, local_max) return max_profit
Python
복사

Optimized Version

class Solution: def maxProfit(self, prices: List[int]) -> int: min_price = float('inf') # 현재까지의 최소 가격 max_profit = 0 # 최대 이익 for price in prices: min_price = min(min_price, price) # 최솟값 갱신 max_profit = max(max_profit, price - min_price) return max_profit
Python
복사
내가 작성한 코드는 loop안에서 list에 대해 max연산을 수행하려면 O(n*n-i)가 걸리고,
따라서 O(n2)시간이 소요됨.
루프를 한번만 돌면서 처리해야한다.
두 숫자간의 min,max연산은 O(1)시간이므로 결과적으로 O(n)시간안에 해결된다.