You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.6 KiB
52 lines
1.6 KiB
package UnitTest;
|
|
|
|
import com.dsideal.QingLong.Util.CommonUtil;
|
|
|
|
import java.util.Arrays;
|
|
|
|
public class TestC {
|
|
|
|
public static int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
|
|
int n = nums.length;
|
|
int[] prefixSum = new int[n + 1];
|
|
for (int i = 1; i <= n; i++) {
|
|
prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
|
|
}
|
|
int maxSum = 0;
|
|
int[] maxSumLeft = new int[n];
|
|
int[] maxSumRight = new int[n];
|
|
int maxLeft = 0, maxRight = 0;
|
|
for (int i = firstLen - 1; i <= n - secondLen; i++) {
|
|
int sum = prefixSum[i + 1] - prefixSum[i - firstLen + 1];
|
|
if (sum > maxLeft) {
|
|
maxLeft = sum;
|
|
}
|
|
maxSumLeft[i] = maxLeft;
|
|
}
|
|
for (int i = n - secondLen; i >= firstLen - 1; i--) {
|
|
int sum = prefixSum[i + secondLen] - prefixSum[i];
|
|
if (sum >= maxRight) {
|
|
maxRight = sum;
|
|
}
|
|
maxSumRight[i] = maxRight;
|
|
}
|
|
for (int i = firstLen - 1; i <= n - secondLen; i++) {
|
|
int sum = prefixSum[i + 1] - prefixSum[i - firstLen + 1];
|
|
maxSum = Math.max(maxSum, sum + maxSumRight[i + 1]);
|
|
maxSum = Math.max(maxSum, sum + maxSumLeft[i - 1]);
|
|
}
|
|
return maxSum;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
int[] nums1 = { 0, 6, 5, 2, 2, 5, 1, 9, 4 };
|
|
int firstLen1 = 1;
|
|
int secondLen1 = 2;
|
|
System.out.println(maxSumTwoNoOverlap(nums1, firstLen1, secondLen1)); // expect 20
|
|
}
|
|
} |