Description
Submission
class Solution {
public:
int maxNonOverlapping(vector<int>& nums, int target) {
int n = nums.size();
nums.insert(nums.begin(), 0);
unordered_map<int, int> Map;
vector<int> presum(n+1, 0);
for(int i = 1; i <= n; ++i) {
presum[i] = presum[i-1] + nums[i];
}
vector<int> dp(n+1, 0);
Map[0] = 0;
for(int i = 1; i <= n; ++i) {
int t = presum[i] - target;
auto iter = Map.find(t);
if(iter == Map.end()) {
dp[i] = dp[i-1];
} else {
int index = iter->second;
dp[i] = max(dp[index] + 1, dp[i-1]);
}
Map[presum[i]]= i;
}
return dp[n];
}
};
References
- https://www.youtube.com/watch?v=-xcIbf0KSgs