3573. Best Time to Buy and Sell Stock V
UnknownView on LeetCode
Time: O(n * k)
Space: O(k)
Problem Overview
Best Time to Buy and Sell Stock V (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Dynamic Programming pattern in coding interviews. DP tracking buy/sell states with at most k transactions and cooldown constraints.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
DP tracking buy/sell states with at most k transactions and cooldown constraints.
Related patterns: Array, Dynamic Programming
3573.cs
C#
// Approach: DP tracking buy/sell states with at most k transactions and cooldown constraints.
// Time: O(n * k) Space: O(k)
public class Solution
{
public long MaximumProfit(int[] prices, int k)
{
int n = prices.Length;
long[] prev = new long[n];
long[] curr = new long[n];
for (int t = 1; t <= k; t++)
{
long bestLong = -prices[0];
long bestShort = prices[0];
curr[0] = 0;
for (int i = 1; i < n; i++)
{
long res = curr[i - 1];
res = Math.Max(res, prices[i] + bestLong);
res = Math.Max(res, -prices[i] + bestShort);
curr[i] = res;
bestLong = Math.Max(bestLong, prev[i - 1] - prices[i]);
bestShort = Math.Max(bestShort, prev[i - 1] + prices[i]);
}
var tmp = prev;
prev = curr;
curr = tmp;
}
return prev[n - 1];
}
}Was this solution helpful?
Related Problems
- 63. Unique Paths II(Medium)
- 85. Maximal Rectangle(Hard)
- 118. Pascal's Triangle(Easy)
- 120. Triangle(Medium)
- 122. Best Time to Buy and Sell Stock II(Medium)
- 174. Dungeon Game(Hard)