Skip to content

Commit 1abd11d

Browse files
authored
Create maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.cpp
1 parent 8a1c950 commit 1abd11d

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int maxNonOverlapping(vector<int>& nums, int target) {
7+
unordered_map<int, int> lookup = {{0, -1}};
8+
int result = 0, accu = 0, right = -1;
9+
for (int i = 0; i < nums.size(); ++i) {
10+
accu += nums[i];
11+
if (lookup.count(accu - target) && lookup[accu - target] >= right) {
12+
right = i;
13+
++result; // greedy
14+
}
15+
lookup[accu] = i;
16+
}
17+
return result;
18+
}
19+
};

0 commit comments

Comments
 (0)