/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public int maxSumTwoNoOverlap(int[] A, int L, int M) {
// Construct prefix sum
// This array contains sum of all contiguous elements
for (int i = 1; i < A.length; i++) {
A[i] = A[i - 1] + A[i];
}
// Assign initial values so we can skip 1st run in below for loop
// Taking the default result to be the first L + M elements
int res = A[L + M - 1];
int maxL = A[L - 1];
int maxM = A[M - 1];
// Either L before M or M before L, start this loop at index L + M
for (int i = L + M; i < A.length; i++) {
// Keep track maxL so far
// L before M: A[i - M] - A[i - M - L] is sum of L-length sub array
maxL
= Math.
max(maxL, A
[i
- M
] - A
[i
- M
- L
]);
// Keep track maxM so far
// M before L: A[i - M] - A[i - L - M] is sum of M-length sub array
maxM
= Math.
max(maxM, A
[i
- L
] - A
[i
- L
- M
]);
// Keep track res so far
// maxL + (A[i] - A[i - M]): Sum of max L-length sub array and current M-length sub array
// maxM + (A[i] - A[i - L]): Sum of max M-length sub array and current L-length sub array
res
= Math.
max(res,
Math.
max(maxL
+ (A
[i
] - A
[i
- M
]), maxM
+ (A
[i
] - A
[i
- L
]))); }
return res;
}
{
// your code goes here
Ideone x = new Ideone();
int[] A = {3, 8, 1, 3, 2, 1, 8, 9, 0};
int L = 3;
int M = 2;
System.
out.
println(x.
maxSumTwoNoOverlap(A, L, M
)); }
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC4qOwppbXBvcnQgamF2YS5sYW5nLio7CmltcG9ydCBqYXZhLmlvLio7CgovKiBOYW1lIG9mIHRoZSBjbGFzcyBoYXMgdG8gYmUgIk1haW4iIG9ubHkgaWYgdGhlIGNsYXNzIGlzIHB1YmxpYy4gKi8KY2xhc3MgSWRlb25lCnsKCXB1YmxpYyBpbnQgbWF4U3VtVHdvTm9PdmVybGFwKGludFtdIEEsIGludCBMLCBp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