- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 85 lines of C++ from the credited upstream file best-time-to-buy-and-sell-stock-v.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 6 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long maximumProfit(vector<int>& prices, int k) {8 static const int64_t NEG_INF = numeric_limits<int64_t>::min();9 10 vector<int64_t> dp(size(prices) + 1);11 int64_t result = 0;12 for (int i = 0; i < k; ++i) {13 vector<int64_t> new_dp(size(prices) + 1, NEG_INF);14 int64_t x = NEG_INF, y = NEG_INF;15 for (int j = i; j < size(prices); ++j) {16 x = max(x, dp[j] - prices[j]);17 y = max(y, dp[j] + prices[j]);18 new_dp[j + 1] = max({new_dp[j], x + prices[j], y - prices[j]});19 }20 dp = move(new_dp);21 result = max(result, dp.back());22 }23 return result;24 }25};26 27282930class Solution2 {31public:32 long long maximumProfit(vector<int>& prices, int k) {33 static const int64_t NEG_INF = numeric_limits<int64_t>::min();34 35 vector<int64_t> bought(k, NEG_INF);36 vector<int64_t> sold(k, NEG_INF);37 vector<int64_t> result(k + 1);38 for (const auto& x : prices) {39 for (int i = k - 1; i >= 0; --i) {40 if (bought[i] != NEG_INF) {41 result[i + 1] = max(result[i + 1], bought[i] + x);42 }43 if (sold[i] != NEG_INF) {44 result[i + 1] = max(result[i + 1], sold[i] - x);45 }46 if (result[i] != NEG_INF) {47 bought[i] = max(bought[i], result[i] - x);48 sold[i] = max(sold[i], result[i] + x);49 }50 }51 }52 return result.back();53 }54};55 56575859class Solution3 {60public:61 long long maximumProfit(vector<int>& prices, int k) {62 static const int64_t NEG_INF = numeric_limits<int64_t>::min();63 64 vector<int64_t> bought(k, NEG_INF);65 vector<int64_t> sold(k, NEG_INF);66 vector<int64_t> result(k + 1, NEG_INF);67 result[0] = 0;68 for (const auto& x : prices) {69 for (int i = k - 1; i >= 0; --i) {70 if (bought[i] != NEG_INF) {71 result[i + 1] = max(result[i + 1], bought[i] + x);72 }73 if (sold[i] != NEG_INF) {74 result[i + 1] = max(result[i + 1], sold[i] - x);75 }76 if (result[i] != NEG_INF) {77 bought[i] = max(bought[i], result[i] - x);78 sold[i] = max(sold[i], result[i] + x);79 }80 }81 }82 return ranges::max(result);83 }84};85