#188
Best Time to Buy and Sell Stock IV
HardArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithm
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(nk) |
| Space | O(1) | O(nk) |
💡
Intuition
Time O(nk)Space O(nk)
The optimal solution uses dynamic programming to keep track of profits for each transaction up to k. This reduces the number of calculations significantly by storing intermediate results.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array dp where dp[i][j] represents the maximum profit on day j with at most i transactions.
- 2Step 2: Iterate through the number of transactions (1 to k) and for each transaction, calculate the maximum profit for each day.
- 3Step 3: Use a variable to track the maximum profit achievable by considering the best buy price seen so far.
solution.py16 lines
1# Full working Python code
2
3def maxProfit(prices, k):
4 if not prices:
5 return 0
6 n = len(prices)
7 if k >= n // 2:
8 return sum(max(prices[i + 1] - prices[i], 0) for i in range(n - 1))
9 dp = [[0] * n for _ in range(k + 1)]
10 for i in range(1, k + 1):
11 max_diff = -prices[0]
12 for j in range(1, n):
13 dp[i][j] = max(dp[i][j - 1], prices[j] + max_diff)
14 max_diff = max(max_diff, dp[i - 1][j] - prices[j])
15 return dp[k][n - 1]
16ℹ
Complexity note: The time complexity is O(nk) because we iterate through each day for each transaction, and the space complexity is O(nk) due to the 2D dp array.
- 1Understanding the difference between brute force and dynamic programming can help you choose the right approach.
- 2Recognizing when to use a greedy approach (when k is large) can simplify the problem significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.