Top Interview 150
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
가 날짜 개념으로 동작한다.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
min_price
를 갱신해준다.min_price
를 뺀 값과 max_profit
을 비교하여 max_profit
을 갱신한다. min_price
는 최대 인덱스 i번의 가격이므로 prices[i]
의 i보다 앞서지 않으므로 조건을 만족한다. for i in range(len(prices))
: min()
, max()
: