Skip to content

Commit 47ac1a8

Browse files
authored
Create 689. Maximum Sum of 3 Non-Overlapping Subarrays (#674)
2 parents 5dd1bea + 2ffbe3f commit 47ac1a8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Solution {
2+
public:
3+
void subarraySum(vector<int>& nums, vector<int>& subarr, int k) {
4+
int n = nums.size();
5+
int l = 0;
6+
int r = 0;
7+
int sum = 0;
8+
9+
while (r < n) {
10+
while (r - l + 1 < k) {
11+
sum += nums[r];
12+
r++;
13+
}
14+
sum += nums[r];
15+
subarr.push_back(sum);
16+
sum -= nums[l];
17+
l++;
18+
r++;
19+
}
20+
};
21+
22+
int helper(int ind, vector<int>& subarr, int k, int count,
23+
vector<vector<int>>& dp) {
24+
int n = subarr.size();
25+
if (count == 0)
26+
return 0;
27+
if (ind >= n)
28+
return INT_MIN;
29+
if (dp[ind][count] != -1)
30+
return dp[ind][count];
31+
int take = subarr[ind] + helper(ind + k, subarr, k, count - 1, dp);
32+
int nottake = helper(ind + 1, subarr, k, count, dp);
33+
return dp[ind][count] = max(take, nottake);
34+
}
35+
void solve(int ind, int count, vector<int>& ans, vector<int>& subarr, int k,
36+
vector<vector<int>>& dp) {
37+
int n = subarr.size();
38+
if (count == 0)
39+
return;
40+
if (ind >= n)
41+
return;
42+
43+
int take = subarr[ind] + helper(ind + k, subarr, k, count - 1, dp);
44+
int nottake = helper(ind + 1, subarr, k, count, dp);
45+
46+
if (take >= nottake) {
47+
ans.push_back(ind);
48+
solve(ind + k, count - 1, ans, subarr, k, dp);
49+
} else
50+
solve(ind + 1, count, ans, subarr, k, dp);
51+
}
52+
53+
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
54+
int n = nums.size();
55+
vector<int> subarr;
56+
subarraySum(nums, subarr, k);
57+
vector<vector<int>> dp(n + 1, vector<int>(4, -1));
58+
vector<int> ans;
59+
solve(0, 3, ans, subarr, k, dp);
60+
return ans;
61+
}
62+
};

0 commit comments

Comments
 (0)