leetcode1031

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, or
0 <= j < j + M - 1 < i < i + L - 1 < A.length.

主要是预处理
s[i] 前i个和
l[i] 前i个中,长度为L的连续子数组和
m[i] 前i个中,长度为M的连续子数组和

f[i] = max(f[i-1],s[i]-s[i-L]+m[i-L],s[i]-s[i-M]+l[i-M])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public int maxSumTwoNoOverlap(int[] A, int L, int M) {
int len = A.length;
int[] l = new int[len];
int[] m = new int[len];
int[] s = new int[len];
int[] f = new int[len];
s[0] = A[0];
for(int i=1;i<len;i++){
s[i] = s[i-1]+A[i];
}
l[L-1] = s[L-1];
for(int i=L;i<len;i++){
l[i] = max(s[i]-s[i-L],l[i-1]);
}
m[M-1] = s[M-1];
for(int i=M;i<len;i++){
m[i] = max(s[i]-s[i-M],m[i-1]);
}
int t = s[L+M-1];
for(int i=M+L;i<len;i++){
t = max(t,max(s[i]-s[i-L]+m[i-L],s[i]-s[i-M]+l[i-M]));
}
return t;
}

private int max(int a,int b){
if (a>b){
return a;
}
return b;
}
}