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 * 1040 <= prices[i] <= 104When 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 solve this problem using the brute force approach, you imagine acting out every single possible combination of buying and selling actions over the entire timeline. You test every scenario of when to purchase and when to cash out to see which set of choices yields the absolute highest total profit.
Here's how the algorithm would work step-by-step:
class Solution:
def maxProfit(self, stock_prices):
def compute_maximum_profit(current_day, is_currently_holding):
if current_day >= len(stock_prices):
return 0
# Explore skipping the current day versus taking action to find all possible paths
skip_current_day = compute_maximum_profit(current_day + 1, is_currently_holding)
if is_currently_holding:
sell_stock_profit = stock_prices[current_day] + compute_maximum_profit(current_day + 1, False)
return max(skip_current_day, sell_stock_profit)
else:
buy_stock_profit = -stock_prices[current_day] + compute_maximum_profit(current_day + 1, True)
return max(skip_current_day, buy_stock_profit)
# Initiate the recursive exploration from the very beginning with no stock currently held
return compute_maximum_profit(0, False)Instead of trying to predict the single best time to buy and sell, the optimal strategy captures every single upward movement in price. By collecting every profitable step along the way, you automatically end up with the maximum possible total profit.
Here's how the algorithm would work step-by-step:
def max_profit(stock_prices):
accumulated_profit = 0
# Iterate through prices starting from the second day to compare with the previous.
for day_index in range(1, len(stock_prices)):
current_price = stock_prices[day_index]
previous_price = stock_prices[day_index - 1]
# Capture every upward price movement to maximize the total accumulated profit.
if current_price > previous_price:
accumulated_profit += current_price - previous_price
# Return the sum of all collected profitable steps from every upward trend.
return accumulated_profit| Case | How to Handle |
|---|---|
| Empty or single-element arrays | Return zero profit immediately because no transaction can be completed without at least two days. |
| Strictly decreasing prices array | The greedy accumulation loop adds zero profit because selling on a lower day than buying is never executed. |
| Strictly increasing prices array | The algorithm accumulates every positive difference between consecutive days, effectively capturing the total span from start to end. |
| Array with all identical prices | All price differences are zero, resulting in a total profit of zero without unnecessary trades. |
| Prices with consecutive valleys and peaks | Summing every upward slope correctly captures all local maxima and minima transactions to maximize total profit. |
| Extremely large arrays approaching maximum memory or time limits | An O(n) time and O(1) space greedy approach iterates through the array once, scaling efficiently without memory overhead. |
| Stock prices with zero values | Since stock prices are non-negative integers, zeros are handled naturally as standard price points without causing arithmetic errors. |
| Very large integers causing potential overflow | Using standard 64-bit integers for the profit accumulator prevents overflow issues even with massive price inputs over large datasets. |