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
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the biggest possible profit, we'll try out every single valid option. This means we will check every possible day to buy the stock and, for each of those days, we'll check every possible future day to sell it.
Here's how the algorithm would work step-by-step:
def maxProfit(prices):
maximum_profit_found = 0
# Iterate through each day as a potential day to buy the stock.
for buy_day_index in range(len(prices)):
# For each buy day, check all subsequent days as potential sell days.
for sell_day_index in range(buy_day_index + 1, len(prices)):
buy_price = prices[buy_day_index]
sell_price = prices[sell_day_index]
potential_profit = sell_price - buy_price
# If this combination yields a better profit, we must update our record of the best one.
if potential_profit > maximum_profit_found:
maximum_profit_found = potential_profit
return maximum_profit_found
The goal is to find the largest possible profit from a single buy and sell transaction. The most efficient way to do this is to go through the historical prices just once, keeping track of the lowest price seen so far and continuously calculating the potential profit if we were to sell on the current day.
Here's how the algorithm would work step-by-step:
def maxProfit(prices):
# Initialize with the first day's price as we need a starting point to compare against.
cheapest_price_so_far = float('inf')
best_profit_so_far = 0
for current_price in prices:
# Calculate profit if we sell today, using the cheapest buy price found before today.
potential_profit = current_price - cheapest_price_so_far
# If today's potential profit is the best we've seen, we update our maximum profit.
if potential_profit > best_profit_so_far:
best_profit_so_far = potential_profit
# Check if the current day's price is a new low, to find better future buy opportunities.
if current_price < cheapest_price_so_far:
cheapest_price_so_far = current_price
return best_profit_so_far
Case | How to Handle |
---|---|
Empty or null input array | The problem constraints typically guarantee a non-empty array, but a robust solution should handle this by returning 0 as no transactions are possible. |
Input array with only one element | No transaction is possible as you cannot buy and sell on the same day, so the maximum profit must be 0. |
Prices are strictly decreasing (e.g., [10, 8, 5, 2]) | The algorithm will correctly find no profitable transaction and return 0, as the max profit will never become positive. |
All prices in the array are identical (e.g., [7, 7, 7, 7]) | The maximum profit will remain 0 throughout the process since the difference between any sell price and the minimum buy price is always zero. |
The minimum price occurs on the last day | No sale can be made after the last day, so the algorithm correctly produces a profit of 0 if all previous prices were higher. |
The maximum price occurs on the first day | The algorithm will set the first price as the initial minimum but will correctly find no profitable selling opportunity if all subsequent prices are lower. |
Large input array size (e.g., 10^5 elements) | A single-pass O(N) solution is efficient and scales linearly, avoiding timeouts that would occur with a brute-force O(N^2) approach. |
Input contains zero as a price | A price of zero is a valid non-negative integer and is handled correctly by the algorithm when tracking the minimum price and calculating profit. |