The trick here is to name the state correctly, then let the implementation follow. For 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target, the solution in this repository is mainly a dynamic programming solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. 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: dynamic programming, prefix sums, greedy.
The notes already sitting in the source point us in the right direction:
- TLE
- 62 / 69 test cases passed.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxNonOverlapping.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- 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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
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
01//TLE
02//62 / 69 test cases passed.
03class Solution {
04public:
05 int maxNonOverlapping(vector<int>& nums, int target) {
06 int n = nums.size();
07
08 vector<int> accsum = nums;
09
10 // cout << accsum[0] << " ";
11 for(int i = 1; i < n; ++i){
12 accsum[i] += accsum[i-1];
13 // cout << accsum[i] << " ";
14 }
15 // cout << endl;
16
17 int cursum = 0;
18 vector<int>::iterator it;
19 vector<pair<int, int>> dp(n); //(count, end)
20 int ans = 0;
21
22 for(int i = 0; i < n; ++i){
23 cursum = (i > 0) ? accsum[i-1] : 0;
24 // cout << "i: " << i << endl;
25 // cout << "cursum: " << cursum << endl;
26 // cout << "finding " << cursum + target << endl;
27 if((it = find(accsum.begin()+i, accsum.end(), cursum+target)) !=
28 accsum.end()){
29 int curend = it - accsum.begin();
30 // cout << "accsum[" << curend << "]: " << accsum[curend] << endl;
31
32 dp[i] = {1, curend};
33 for(int j = 0; j < i; ++j){
34 if(dp[j].second < i && dp[j].first >= 1){
35 //no overlap
36 dp[i] = {dp[j].first+1, curend};
37 }
38 }
39
40 // cout << "[" << i << ", " << dp[i].second << "]: " << dp[i].first << endl; //"\t";
41 ans = max(ans, dp[i].first);
42 }
43 }
44 // cout << endl;
45
46 return ans;
47 }
48};
49
50//improved from above, using unordered_map
51//TLE
52//66 / 69 test cases passed.
53class Solution {
54public:
55 int maxNonOverlapping(vector<int>& nums, int target) {
56 int n = nums.size();
57
58 vector<int> accsum = nums;
59 unordered_map<int, vector<int>> accsum2idx;
60
61 // cout << accsum[0] << " ";
62 accsum2idx[accsum[0]].push_back(0);
63 for(int i = 1; i < n; ++i){
64 accsum[i] += accsum[i-1];
65 accsum2idx[accsum[i]].push_back(i);
66 // cout << accsum[i] << " ";
67 }
68 // cout << endl;
69
70 int cursum = 0;
71 vector<int>::iterator it;
72 vector<pair<int, int>> dp(n); //(count, end)
73 int ans = 0;
74
75 for(int i = 0; i < n; ++i){
76 cursum = (i > 0) ? accsum[i-1] : 0;
77 // cout << "i: " << i << endl;
78 // cout << "cursum: " << cursum << endl;
79 // cout << "finding " << cursum + target << endl;
80 // if((it = find(accsum.begin()+i, accsum.end(), cursum+target)) !=
81 // accsum.end()){
82
83 while(!accsum2idx[cursum+target].empty() && accsum2idx[cursum+target].front() < i){
84 accsum2idx[cursum+target].erase(accsum2idx[cursum+target].begin());
85 }
86 if(!accsum2idx[cursum+target].empty()){
87 int curend = accsum2idx[cursum+target].front();
88 // int curend = it - accsum.begin();
89 // cout << "accsum[" << curend << "]: " << accsum[curend] << endl;
90
91 dp[i] = {1, curend};
92 for(int j = i-1; j >= 0; --j){
93 if(dp[j].second < i && dp[j].first >= 1){
94 //no overlap
95 dp[i] = {dp[j].first+1, curend};
96 break;
97 }
98 }
99
100 // cout << "[" << i << ", " << dp[i].second << "]: " << dp[i].first << endl; //"\t";
101 ans = max(ans, dp[i].first);
102 }
103 }
104 // cout << endl;
105
106 return ans;
107 }
108};
109
110//greedy, hashmap
111//https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/780887/Java-Detailed-Explanation-DPMapPrefix-O(N)
112//Runtime: 400 ms, faster than 100.00% of C++ online submissions for Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.
113//Memory Usage: 82.9 MB, less than 50.00% of C++ online submissions for Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.
114class Solution {
115public:
116 int maxNonOverlapping(vector<int>& nums, int target) {
117 int n = nums.size();
118 /*
119 unordered_map's search/insertion/deletion time:
120 average O(1), worst O(n)
121 */
122 unordered_map<int, int> sum2count;
123 int sum = 0;
124 int count = 0;
125
126 /*
127 if we can find a i s.t. nums[0...i] = target,
128 count should be sum2count[0]+1 = 1
129 */
130 sum2count[0] = 0;
131
132 for(int i = 0; i < n; ++i){
133 //sum: accumulate sum of nums[0...i]
134 sum += nums[i];
135
136 if(sum2count.find(sum-target) != sum2count.end()){
137 /*
138 we can find a j s.t. nums[0...j] + target = nums[0...i],
139 so nums[j+1...i] sums to target
140 */
141 //choose btw original count and current found count
142 count = max(count, sum2count[sum-target] + 1);
143 }
144
145 sum2count[sum] = count;
146 }
147
148 return count;
149 }
150};
Cost