You are given an array prices where prices[i]
is the price of a given stock on the ith
day. Find the maximum profit you can achieve. You may complete at most two transactions
. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
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.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^5
There are multiple DP approach but I found this approach so simple. We need to have two arrays with the size of k
to store minimum price and profits at the ith
transaction. So, the first element of the arrays always get upadated per each price in the prices
array. This solution has a time complexity of O(Nk)
and space complexity of O(k)
where N
is the size of prices
array and k
is the number of transactions.
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
:Time Complexity: O(N)
:Space Complexity: O(1)
"""
if len(prices) == 0:
return 0
k = 2
min_price = [float("inf")] * k
profit = [float("-inf")] * k
for price in prices:
min_price[0] = min(min_price[0], price)
profit[0] = max(profit[0], price - min_price[0])
for i in range(1, k):
min_price[i] = min(min_price[i], price - profit[i - 1])
profit[i] = max(profit[i], price - min_price[i])
return profit[-1]
For the second solution, we can try to have a 2D
array for DP; 1 row per transactions including the transcation zero. Similarly, this solution has a time complexity of O(N)
while it has a space complexity of O(N)
as well.
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
:Time Complexity: O(N)
:Space Complexity: O(N)
"""
if len(prices) == 0:
return 0
k = 2
max_profit = 0
dp = [[0 for j in range(len(prices))] for i in range(k + 1)]
for i in range(1, k + 1):
maxpr = -prices[0]
for j in range(1, len(prices)):
dp[i][j] = max(dp[i][j - 1], maxpr + prices[j])
maxpr = max(maxpr, -prices[j] + dp[i - 1][j])
return dp[-1][-1]