You are given an integer array prices
where prices[i]
is the price of a given stock on the i<sup>th</sup>
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. Let's walk through a few examples.
Example 1:
prices = [7,1,5,3,6,4]
Here's how one might derive the answer:
Example 2:
prices = [1,2,3,4,5]
Here's how one might derive the answer:
Example 3:
prices = [7,6,4,3,1]
Here's how one might derive the answer:
With these examples in mind, how would you go about implementing the function to find the maximum profit?
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 most profit from stock trades, the brute force method considers every single possible combination of buying and selling. It's like going through every 'what if' scenario to see which one makes the most money. We’ll check all buy/sell options to determine the maximum profit.
Here's how the algorithm would work step-by-step:
def max_profit_brute_force(prices):
def calculate_max_profit(prices, start_day):
# Base case: If we reach the end of the list, there's no profit
if start_day >= len(prices):
return 0
max_profit = 0
for current_day in range(start_day, len(prices)):
max_profit_from_current_day = 0
# Try selling on each day after the current day
for selling_day in range(current_day + 1, len(prices)):
if prices[selling_day] > prices[current_day]:
# Calculate profit from this transaction
current_profit = prices[selling_day] - prices[current_day]
# Recursively calculate profit from future transactions after selling.
current_profit += calculate_max_profit(prices, selling_day + 1)
max_profit_from_current_day = max(max_profit_from_current_day, current_profit)
max_profit = max(max_profit, max_profit_from_current_day)
return max_profit
# Start the calculation from the beginning of the price list.
return calculate_max_profit(prices, 0)
The goal is to make as much profit as possible by buying and selling stock. The optimal strategy focuses on identifying every profitable rise in stock price and capitalizing on it immediately, instead of trying to predict larger, potentially missed gains.
Here's how the algorithm would work step-by-step:
def max_profit_from_stock(prices):
max_profit = 0
# Iterate through the prices starting
# from the second day.
for i in range(1, len(prices)):
# Check if today's price is higher
# than yesterday's price.
if prices[i] > prices[i - 1]:
# If it is, calculate the profit
# and add it to the total profit.
profit = prices[i] - prices[i - 1]
max_profit += profit
return max_profit
Case | How to Handle |
---|---|
Empty input array | Return 0, as no transactions are possible with no prices. |
Array with only one price | Return 0, as a single day doesn't allow for a buy and sell. |
Prices are in strictly decreasing order | Return 0, as there are no profitable buying opportunities. |
Prices are in strictly increasing order | Calculate profit as price[n-1] - price[0], effectively buying on day 0 and selling on day n-1. |
Array with duplicate consecutive prices | The algorithm should correctly ignore consecutive days with same prices, only considering price changes. |
Large input array leading to potential integer overflow in profit calculation | Use a data type that can accommodate large profits (e.g., long long in C++ or long in Java) or handle potential overflow with checks. |
Input array with very small price fluctuations | The algorithm should still work correctly, summing all positive price differences. |
Input array with very large price fluctuations | The algorithm should still work correctly, summing all positive price differences assuming there is no overflow. |