Skip to content

Commit 49d3e8b

Browse files
authored
Create find-two-non-overlapping-sub-arrays-each-with-target-sum.cpp
1 parent 039feac commit 49d3e8b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minSumOfLengths(vector<int>& arr, int target) {
7+
unordered_map<int, int> prefix = {{0, -1}};
8+
vector<int> dp(arr.size());
9+
int result = numeric_limits<int>::max(), min_len = numeric_limits<int>::max();
10+
int accu = 0;
11+
for (int right = 0; right < arr.size(); ++right) {
12+
accu += arr[right];
13+
prefix[accu] = right;
14+
if (prefix.count(accu - target)) {
15+
auto left = prefix[accu - target];
16+
min_len = min(min_len, right - left);
17+
if (left != -1 && dp[left] != numeric_limits<int>::max()) {
18+
result = min(result, dp[left] + (right - left));
19+
}
20+
}
21+
dp[right] = min_len;
22+
}
23+
return result != numeric_limits<int>::max() ? result : -1;
24+
}
25+
};

0 commit comments

Comments
 (0)