Given an array A
of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L
and M
. (For clarification, the L
-length subarray could occur before or after the M
-length subarray.)
Formally, return the largest V
for which V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1])
and either:
0 <= i < i + L - 1 < j < j + M - 1 < A.length
, or0 <= j < j + M - 1 < i < i + L - 1 < A.length
.
Example:
Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
Approach:
C++
#include <bits/stdc++.h>using namespace std;int maxSumTwoNoOverlap(vector<int> &A, int l, int m){vector<int> sum;int s = 0;for (int i = 0; i < A.size(); i++){s += A[i];sum.push_back(s);}vector<int> pre(A.size(), 0);vector<int> suf(A.size(), 0);pre[l - 1] = sum[l - 1];for (int i = l; i < A.size(); i++){pre[i] = max(pre[i - 1], sum[i] - sum[i - l]);}suf[A.size() - m] = sum[A.size() - 1] - sum[A.size() - m - 1];for (int i = A.size() - m - 1; i > 0; i--){suf[i] = max(suf[i + 1], sum[i + m - 1] - sum[i - 1]);}int ans = 0;for (int i = l - 1; i + 1 < A.size(); i++){ans = max(ans, pre[i] + suf[i + 1]);}pre.resize(A.size(), 0);suf.resize(A.size(), 0);swap(l, m);pre[l - 1] = sum[l - 1];for (int i = l; i < A.size(); i++){pre[i] = max(pre[i - 1], sum[i] - sum[i - l]);}suf[A.size() - m] = sum[A.size() - 1] - sum[A.size() - m - 1];for (int i = A.size() - m - 1; i > 0; i--){suf[i] = max(suf[i + 1], sum[i + m - 1] - sum[i - 1]);}for (int i = l - 1; i + 1 < A.size(); i++){ans = max(ans, pre[i] + suf[i + 1]);}return ans;}int main(){vector<int> A = {0, 6, 5, 2, 2, 5, 1, 9, 4};int L = 1, M = 2;cout << maxSumTwoNoOverlap(A, L, M);return 0;}
No comments:
Post a Comment