#3573
Best Time to Buy and Sell Stock V
MediumArrayDynamic ProgrammingHash MapArray
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)
Using dynamic programming, we can build a table to store the maximum profit for each transaction limit and day, allowing us to efficiently compute profits without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP table where dp[t][d] represents max profit with t transactions by day d.
- 2Step 2: Iterate through each transaction limit and each day, calculating profits based on previous days.
- 3Step 3: Return the maximum profit from the last transaction on the last day.
solution.py11 lines
1def maxProfit(prices, k):
2 if not prices: return 0
3 n = len(prices)
4 if k >= n // 2: return sum(max(prices[i+1] - prices[i], 0) for i in range(n-1))
5 dp = [[0] * n for _ in range(k + 1)]
6 for t in range(1, k + 1):
7 max_diff = -prices[0]
8 for d in range(1, n):
9 dp[t][d] = max(dp[t][d-1], prices[d] + max_diff)
10 max_diff = max(max_diff, dp[t-1][d] - prices[d])
11 return dp[k][n-1]ℹ
Complexity note: The time complexity is O(nk) due to iterating through n days for k transactions, while space complexity is O(nk) for the DP table.
- 1Dynamic programming can optimize recursive solutions.
- 2Understanding transaction types helps in formulating the DP approach.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.