Problem solution · C++

Best Time to Buy and Sell Stock V

Best Time to Buy and Sell Stock V: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
85 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Best Time to Buy and Sell Stock V, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeBest Time to Buy and Sell Stock V · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n * k)// Space: O(k) // dpclass Solution {public:    long long maximumProfit(vector<int>& prices, int k) {        static const int64_t NEG_INF = numeric_limits<int64_t>::min();         vector<int64_t> dp(size(prices) + 1);        int64_t result = 0;        for (int i = 0; i < k; ++i) {            vector<int64_t> new_dp(size(prices) + 1, NEG_INF);            int64_t x = NEG_INF, y = NEG_INF;            for (int j = i; j < size(prices); ++j) {                x = max(x, dp[j] - prices[j]);                y = max(y, dp[j] + prices[j]);                new_dp[j + 1] = max({new_dp[j], x + prices[j], y - prices[j]});            }            dp = move(new_dp);            result = max(result, dp.back());        }        return result;    }}; // Time:  O(n * k)// Space: O(k)// dpclass Solution2 {public:    long long maximumProfit(vector<int>& prices, int k) {        static const int64_t NEG_INF = numeric_limits<int64_t>::min();         vector<int64_t> bought(k, NEG_INF);        vector<int64_t> sold(k, NEG_INF);        vector<int64_t> result(k + 1);        for (const auto& x : prices) {            for (int i = k - 1; i >= 0; --i) {                if (bought[i] != NEG_INF) {                    result[i + 1] = max(result[i + 1], bought[i] + x);                }                if (sold[i] != NEG_INF) {                    result[i + 1] = max(result[i + 1], sold[i] - x);                }                if (result[i] != NEG_INF) {                    bought[i] = max(bought[i], result[i] - x);                    sold[i] = max(sold[i], result[i] + x);                }            }        }        return result.back();    }}; // Time:  O(n * k)// Space: O(k)// dpclass Solution3 {public:    long long maximumProfit(vector<int>& prices, int k) {        static const int64_t NEG_INF = numeric_limits<int64_t>::min();         vector<int64_t> bought(k, NEG_INF);        vector<int64_t> sold(k, NEG_INF);        vector<int64_t> result(k + 1, NEG_INF);        result[0] = 0;        for (const auto& x : prices) {            for (int i = k - 1; i >= 0; --i) {                if (bought[i] != NEG_INF) {                    result[i + 1] = max(result[i + 1], bought[i] + x);                }                if (sold[i] != NEG_INF) {                    result[i + 1] = max(result[i + 1], sold[i] - x);                }                if (result[i] != NEG_INF) {                    bought[i] = max(bought[i], result[i] - x);                    sold[i] = max(sold[i], result[i] + x);                }            }        }        return ranges::max(result);    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗