Buy and Sell Stock
Maximize Stock Trading Profit. You are given a sequence of stock prices representing the value of a particular stock on consecutive days. You can complete as many transactions as you like with the following constraints:
- You must buy before you sell.
- You cannot buy on one day and sell on the same day (buying and selling in the same day counts as nothing).
Maximize your profit given these conditions.
For example, consider the following stock prices over a week: 1, 2, 3, 4, 5. If you buy on day 1 and sell on day 5, your profit will be 4 (buy at 1 and sell at 5).
Examples
stock_prices = [7, 1, 5, 3, 6, 4] output: 7 (Buy on day 2 at 1, sell on day 3 at 5, buy on day 4 at 3, and sell on day 5 at 6) stock_prices = [1, 2, 3, 4, 5] output: 4 (Buy on day 1 at 1 and sell on day 5 at 5) stock_prices = [7, 6, 4, 3, 1] output: 0 (No transaction is done, i.e., max profit = 0) stock_prices = [1, 10, 2, 3] output: 9 (Buy on day 1 at 1 and sell on day 2 at 10)
The goal of this solution is to maximize profit by buying and selling stocks on different days, given an array of stock prices where each element represents the price of the stock on a particular day.
The algorithm uses a greedy approach with a min-heap (implemented as a priority queue) to keep track of the lowest prices encountered so far. By maintaining a collection of potential buy prices, we can ensure that we always buy at the lowest possible price and sell at a higher price later, thereby maximizing profit.
Here's a step-by-step explanation of the approach:
-
Initialize Data Structures: Use a priority queue (
options) to act as a min-heap to store the prices of stocks. InitializecurrentProfitto 0, which will store the accumulated profit. -
Iterate Through the Stock Prices: For each price in the
stockPricesarray:- If the current price is higher than the lowest price in the heap (
options.peek()), compute the profit by selling at the current price and buying at the lowest price. UpdatecurrentProfitaccordingly. - Remove the lowest price from the heap after using it for profit calculation.
- Push the current price into the heap as a potential buy price.
- If the current price is higher than the lowest price in the heap (
-
Return the Total Profit: After iterating through all the prices, return the accumulated
currentProfit.
This approach ensures that we always buy low and sell high, using the min-heap to efficiently manage and access the lowest prices encountered.
import heapq
def max_profit_greedy(stock_prices):
# options will act as a min-heap to store the stock prices encountered so far
options = []
# Initialize current_profit to accumulate the total profit
current_profit = 0
# Iterate through each price in the list of stock prices
for price in stock_prices:
# Check if there is any price in the options and if the current price is higher
# than the smallest price in the options (heap)
if len(options) > 0 and price > options[0]:
# If the condition is true, calculate the profit by subtracting the smallest
# price in the heap from the current price and add it to current_profit
current_profit += price - options[0]
# Remove the smallest price from the heap as it has been used to make a profit
heapq.heappop(options)
# Push the current price into the heap (options) to consider it for future transactions
heapq.heappush(options, price)
# Return the total accumulated profit
return current_profitTime Complexity: Inserting a price into the min-heap and removing the smallest price both take O(log n) time, where n is the number of elements in the heap. Since we perform these operations for each of the n prices in the stockPrices array, the overall time complexity is O(n log n).
Space Complexity: The space complexity is dominated by the storage required for the heap. In the worst case, we might store all n prices in the heap, leading to a space complexity of O(n).
In this video, Lewin (Dropbox SWE) answers an interview question about the best times to buy and sell stock.
public static int maxProfitGreedy(int[] stockPrices) { int maxProfit = 0; for(int i = 1; i < stockPrices.length; i++) { int todayPrice = stockPrices[i-1]; int tomorrowPrice = stockPrices[i]; if(tomorrowPrice > todayPrice) { maxProfit += tomorrowPrice - todayPrice; } } return maxProfit; }