You are given an array prices
where prices[i]
is the price of a given stock on the i-th
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.
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.
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
min_price
: a variable to store the minimum price encountered so far, initialized to a high value (infinity).max_profit
: a variable to store the maximum profit observed so far, initialized to 0.min_price
if the current price is lower than min_price
.current_profit
as the difference between the current price and min_price
.max_profit
if current_profit
is greater than max_profit
.max_profit
will hold the highest profit possible.Here is the implementation of the described strategy:
def maxProfit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
return max_profit
prices
array. This is because we iterate through the list exactly once.This solution efficiently finds the maximum profit in linear time while maintaining constant space usage.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?