← Home

1425. Constrained Subsequence Sum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
142

This is one of those problems where the clean idea matters more than the amount of code. For 1425. Constrained Subsequence Sum, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue, dynamic programming, sliding window.

The notes already sitting in the source point us in the right direction:

  • sliding window, dp, heap

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are constrainedSubsetSum.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//sliding window, dp, heap
02//Runtime: 396 ms, faster than 33.09% of C++ online submissions for Constrained Subsequence Sum.
03//Memory Usage: 50 MB, less than 100.00% of C++ online submissions for Constrained Subsequence Sum.
04class Solution {
05public:
06    int constrainedSubsetSum(vector<int>& nums, int k) {
07        int n = nums.size();
08        vector<int> dp(n);
09        deque<int> window;
10        //(dp[index], index)
11        priority_queue<pair<int, int>, vector<pair<int, int>>> windowHeap;
12        int ans = INT_MIN;
13        
14        for(int i = 0; i < n; i++){
15            //window contains the dp value from dp[i-k] to dp[i-1]
16            // dp[i] = nums[i] + (window.size() > 0 ? *max_element(window.begin(), window.end()) : 0);
17            int windowMax = 0;
18            if(window.size() > 0){
19                pair<int, int> p = windowHeap.top();
20                while(p.second < i-k){
21                    //it's outside the window
22                    windowHeap.pop();
23                    p = windowHeap.top();
24                }
25                windowMax = p.first;
26            }
27            dp[i] = nums[i] + windowMax;
28            
29            ans = max(ans, dp[i]);
30            
31            //update sliding window
32            if(window.size() == k){
33                window.pop_front();
34            }
35            
36            if(dp[i] >= 0){
37                window.push_back(dp[i]);
38                windowHeap.push(make_pair(dp[i], i));
39            }
40            
41        }
42        
43        //max dp value from dp[n-1] to dp[n-k]
44        // return *max_element(window.begin(), window.end());
45        // return dp.back();
46        // return *max_element(dp.begin(), dp.end());
47        return ans;
48    }
49};
50
51//sliding window, dp, decreasing deque
52//https://leetcode.com/problems/constrained-subsequence-sum/discuss/597751/JavaC%2B%2BPython-O(N)-Decreasing-Deque
53//Runtime: 168 ms, faster than 67.18% of C++ online submissions for Constrained Subsequence Sum.
54//Memory Usage: 40.9 MB, less than 100.00% of C++ online submissions for Constrained Subsequence Sum.
55class Solution {
56public:
57    int constrainedSubsetSum(vector<int>& nums, int k) {
58        int n = nums.size();
59        deque<int> window;
60        vector<int> dp(n, 0);
61        int ans = INT_MIN;
62        
63        for(int i = 0; i < n; i++){
64            /*
65            deque stores the dp value from dp[i-1] to dp[i-k],
66            in decreasing order
67            */
68            dp[i] = nums[i] + ((window.size() > 0) ? window.front() : 0);
69            //cout << dp[i] << " ";
70            ans = max(ans, dp[i]);
71            
72            /*
73            we only use the deque to extract max dp value,
74            so if current dp value are largest,
75            the stored dp values are useless
76            
77            every elements in the deque < dp[i] will be discarded,
78            so dp[i] will be the smallest value in the deque,
79            and we may push dp[i] to the back of the deque,
80            so we can say that the deque is decreasing
81            */
82            while(window.size() > 0 && dp[i] > window.back()){
83                window.pop_back();
84            }
85            
86            /*
87            we can discard negative dp value,
88            for example, suppose we are calculating dp[3],
89            but dp[0], dp[1], and dp[2] are negative,
90            then we set dp[3] as nums[3],
91            that means we discard all former values,
92            and set the start of the window at index 3
93            */
94            if(dp[i] > 0){
95                window.push_back(dp[i]);
96            }
97            
98            /*
99            prepare for next iteration,
100            discard dp value out of window
101            
102            it seems the size of window is not important, 
103            we just want to make sure that 
104            when we are calculating new dp[i], 
105            window.front() is one of dp[i-1]...dp[i-k],
106            */
107            if(window.size() > 0 && i-k >= 0 && window.front() == dp[i-k]){
108                window.pop_front();
109            }
110        }
111        
112        return ans;
113    }
114};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.