You are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.
Example 3:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
Constraints:
1 <= prices.length <= 3 * 104
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:
The problem is about finding the maximum profit from buying and selling a stock, allowing multiple transactions. The brute force strategy explores every single possible sequence of buy and sell actions. It checks all combinations to find the one with the highest profit.
Here's how the algorithm would work step-by-step:
def max_profit_brute_force(prices):
def calculate_max_profit(prices, current_index, holding_stock):
# Base case: reached the end of the prices list
if current_index >= len(prices):
return 0
# Option 1: Do nothing on this day
profit_if_do_nothing = calculate_max_profit(prices, current_index + 1, holding_stock)
profit_if_buy = 0
profit_if_sell = 0
#If not holding, can consider buying
if not holding_stock:
profit_if_buy = -prices[current_index] + calculate_max_profit(prices, current_index + 1, True)
#If holding, can consider selling
else:
profit_if_sell = prices[current_index] + calculate_max_profit(prices, current_index + 1, False)
return max(profit_if_do_nothing, profit_if_buy, profit_if_sell)
# Initiate recursion.
# Start from the beginning with no stock.
return calculate_max_profit(prices, 0, False)
The key idea is to maximize profit by buying low and selling high whenever possible. We don't need to find the absolute lowest buy price and highest sell price overall; we can simply accumulate profits from all the increasing price intervals.
Here's how the algorithm would work step-by-step:
def max_profit(prices):
maximum_profit = 0
# Iterate through the prices, starting from the second day
for i in range(1, len(prices)):
# Check if the current day's price is higher than the previous day's price
if prices[i] > prices[i - 1]:
# Accumulate profit if today's price exceeds yesterday's.
maximum_profit += prices[i] - prices[i - 1]
# Return the maximum profit that can be obtained
return maximum_profit
Case | How to Handle |
---|---|
Empty or null 'prices' array | Return 0 as no profit can be made with no prices. |
'prices' array with only one element | Return 0 as no transaction (buy and sell) can occur. |
'prices' array with two elements, decreasing order | Return 0 as there is no opportunity to make a profit (price decreased). |
'prices' array with all identical values | Return 0 as there's no price fluctuation, so no profit. |
'prices' array with monotonically increasing values | The algorithm should correctly sum the differences between consecutive days to maximize profit in this ideal scenario. |
'prices' array with monotonically decreasing values | The algorithm correctly returns zero profit since no transaction is profitable. |
'prices' array with a mix of increasing and decreasing values, large range | Greedy approach correctly accumulates profits from all increasing subsequences. |
Large 'prices' array with integer overflow potential in profit calculation (if using certain languages) | Use appropriate data types (e.g., long) to prevent integer overflow during profit calculation, or use modulo if relevant. |