Key takeaways
The Best Time to Buy and Sell Stock II problem aims to maximize profits from stock trading over multiple days, allowing for multiple buy/sell transactions.
You can hold only one share of stock at any time and buy/sell on the same day.
The approach to solving this problem involves iterating through the price list, capturing profits whenever the current day's price exceeds the previous day's price. Add the difference between consecutive days' prices to a running total of profit whenever a profitable opportunity is identified.
The time complexity is
, where n is the length of the prices array. The space complexity is
.
This a classic algorithmic challenge that tests our ability to maximize profits from stock trading over a series of days. Unlike the simpler version, where we can only make one transaction (buy and sell once), this problem allows for multiple transactions (buy and sell multiple times). Only one share can be held of the stock at any time is the key constraint of this problem.
We have an array of integers, prices
, where prices[i]
represents the price of a particular stock on the
Determine and return the maximum profit we can achieve.
Constraints
prices.length
prices[i]
Let’s gain a better understanding of the problem with the following examples:
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving it correctly:
Best Time to Buy and Sell Stock II
What should be the output if the following prices are given as an input?
prices = [3, 3, 5, 0, 0, 3, 1, 4]
5
8
7
4
To solve this problem, we can use a simple idea to capture all the profitable opportunities by considering every upward price movement as a potential profit. The algorithm walks through the following steps:
We initialize a variable, profit
, with
We start iterating from the second day of the prices
list, and in each iteration, we perform the following steps:
We compare the price of each day with the price of the previous day.
If the price of the current day is higher than the price of the previous day, it means there is an opportunity to buy the stock on the previous day and make a profit, and then sell it on the current day.
We add the difference between the price of the current day and the price of the previous day to profit
.
We return the total profit stored in profit
.
This approach ensures that we capture all the small profits that add up to the maximum possible profit. Let’s look at the following illustration for a better understanding.
Let’s look at the code for the algorithm we just discussed.
def maxProfit(prices):# Initialize the total profit with 0profit = 0# Traverse the list of pricesfor i in range(1, len(prices)):if prices[i] > prices[i - 1]:# Determine the profit from buying on previous day and selling on current dayprofit += prices[i] - prices[i - 1]return profitdef main():pricesList = [[7,1,5,3,6,4],[1,7,2,8,4,9],[8, 3, 5, 2, 4, 6, 0, 1],[2,3,4,5,6],[7,6,4,3,1]]i = 1for x in pricesList:print(i, ".\tPrices: ", x, sep = "")print("\n\tProfit: ", maxProfit(x), sep = "")print("-"*100, "\n", sep = "")i+=1if __name__ == "__main__":main()
Now, let’s look at the time and space complexity of the solution.
The time complexity of the solution is prices
array. The algorithm only requires a single pass through the array to compute the total profit.
The space complexity of the solution is
Free Resources