# 【滑窗】B021_LC_兩個非重疊子數組的最大和（分類討論 / 優化）

## 一、Problem

0 <= i < i + L - 1 < j < j + M - 1 < A.length, 或
0 <= j < j + M - 1 < i < i + L - 1 < A.length.

輸入：A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2



• L >= 1
M >= 1
L + M <= A.length <= 1000
0 <= A[i] <= 1000

## 二、Solution

### 方法一：分類討論

• 在 L 的左側
• 在 L 的右側

class Solution {
public int maxSumTwoNoOverlap(int[] A, int L, int M) {
int n = A.length, s[] = new int[n+1];
for (int i = 1; i <= n; i++)
s[i] = s[i-1] + A[i-1];

int ans = 0;
for (int i = L; i <= n; i++) {
int maxM = 0;
for (int j = M; j < i-L; j++)
maxM = Math.max(maxM, s[j] - s[j-M]);
for (int j = i+M; j <= n; j++)
maxM = Math.max(maxM, s[j] - s[j-M]);
ans = Math.max(ans, s[i] - s[i-L] + maxM);
}
return ans;
}
}


• 時間複雜度：$O(n^2)$
• 空間複雜度：$O(n)$

### 方法二：優化

class Solution {
public int maxSumTwoNoOverlap(int[] A, int L, int M) {
int n = A.length, s[] = new int[n+1];
for (int i = 1; i <= n; i++)
s[i] = s[i-1] + A[i-1];

int ans = 0, maxL = 0, maxR = 0;
for (int i = L; i <= n-M; i++) {
maxL = Math.max(maxL, s[i] - s[i-L]);
ans = Math.max(ans, maxL + s[i+M] - s[i]);
}
for (int i = M; i <= n-L; i++) {
maxR = Math.max(maxR, s[i] - s[i-M]);
ans = Math.max(ans, maxR + s[i+L] - s[i]);
}
return ans;
}
}


• 時間複雜度：$O(n)$
• 空間複雜度：$O(n)$