一、题目描述
二、代码
public class Solution_1031 {
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
return Math.max(compute(nums, firstLen, secondLen), compute(nums, secondLen, firstLen));
}
public int compute(int[] nums, int first, int second) {
int sumF = 0; //表示当前位置往前first个数的和
//计算前first个数的和
for (int i = 0; i < first; ++i) {
sumF += nums[i];
}
int maxSumF = sumF; //maxSumF表示当前坐标中first子数组的最大和
int sumS = 0; //表示第二个子数组的和
for (int i = first; i < first + second; ++i) {
sumS += nums[i];
}
int res = maxSumF + sumS;
for (int i = first, j = first + second; j < nums.length; ++i, ++j){
sumF += nums[i] - nums[i - first];
maxSumF = Math.max(maxSumF, sumF);
sumS += nums[j] - nums[j - second];
res = Math.max(res, maxSumF + sumS);
}
return res;
}
}
三、思路
两个子数组先后顺序没有要求,因此针对firstLen数组在前进行考虑。
使用maxSumF记录第一个子数组的最大和,在移动过程中不断更新。
使用sumR记录当前第二个子数组的和,取res和当前maxSumF + sumS的最大值。
四、一些疑惑
最大值不应该是当前第一个子数组的最大值加上第二个子数组和的最大值,为什么只计算了紧跟着当前下标的长度为secondL的子数组的和呢?
这是因为在遍历过程中,第二个子数组的所有可能值都会被遍历到,且maxS始终加上的是第一个子数组的最大值,因此得到的结果必为正解。