Problem solution · C++

Count Partitions with Max Min Difference at Most K

Count Partitions with Max Min Difference at Most K: 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
37 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 Count Partitions with Max Min Difference at Most K, 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

  • 37 lines of C++ from the credited upstream file count-partitions-with-max-min-difference-at-most-k.cpp.
  • The implementation visibly relies on sequence storage, work queue, cached states.
  • 4 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 codeCount Partitions with Max Min Difference at Most K · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n)// Space: O(n) // mono deque, two pointers, sliding window, dp, prefix sumclass Solution {public:    int countPartitions(vector<int>& nums, int k) {        static const int MOD = 1e9 + 7;         deque<int> max_dq, min_dq;        vector<int> dp(size(nums) + 1);        dp[0] = 1;        for (int right = 0, left = 0, suffix = 0; right < size(nums); ++right) {            suffix = (suffix + dp[right]) % MOD;            while (!empty(max_dq) && nums[max_dq.back()] <= nums[right]) {                max_dq.pop_back();            }            max_dq.emplace_back(right);            while (!empty(min_dq) && nums[min_dq.back()] >= nums[right]) {                min_dq.pop_back();            }            min_dq.emplace_back(right);            while (nums[max_dq[0]] - nums[min_dq[0]] > k) {                if (max_dq[0] == left) {                    max_dq.pop_front();                }                if (min_dq[0] == left) {                    min_dq.pop_front();                }                suffix = (((suffix - dp[left++]) % MOD) + MOD) % MOD;            }            dp[right + 1] = suffix;        }        return dp.back();    }}; 

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 ↗