You are given an integer array prices where prices[i]
is the price of a given stock on the ith
day, and an integer k
. Find the maximum profit you can achieve. You may complete at most k
transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
0 <= k <= 100
0 <= prices.length <= 1000
0 <= prices[i] <= 1000
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(k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
:Time Complexity: O(N * k)
:Space Complexity: O(k)
"""
if k == 0 or len(prices) == 0:
return 0
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(Nk)
while it has a space complexity of O(Nk)
as well.
def maxProfit(k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
:Time Complexity: O(N * k)
:Space Complexity: O(N * k)
"""
if k == 0 or len(prices) == 0:
return 0
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]