Compare commits

...

2 Commits

@ -6,47 +6,47 @@ import java.util.Arrays;
public class TestC { public class TestC {
public static String[] sortByName(String[] names, int[] heights) { public static int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
quickSort(names, heights, 0, heights.length - 1); int n = nums.length;
return names; int[] prefixSum = new int[n + 1];
} for (int i = 1; i <= n; i++) {
prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
private static void quickSort(String[] names, int[] heights, int start, int end) {
if (start >= end) {
return;
} }
int pivot = partition(names, heights, start, end); int maxSum = 0;
quickSort(names, heights, start, pivot - 1); int[] maxSumLeft = new int[n];
quickSort(names, heights, pivot + 1, end); int[] maxSumRight = new int[n];
} int maxLeft = 0, maxRight = 0;
for (int i = firstLen - 1; i <= n - secondLen; i++) {
private static int partition(String[] names, int[] heights, int start, int end) { int sum = prefixSum[i + 1] - prefixSum[i - firstLen + 1];
int pivotHeight = heights[end]; if (sum > maxLeft) {
int i = start - 1; maxLeft = sum;
for (int j = start; j < end; j++) { }
if (heights[j] >= pivotHeight) { maxSumLeft[i] = maxLeft;
i++; }
int tmpHeight = heights[i]; for (int i = n - secondLen; i >= firstLen - 1; i--) {
heights[i] = heights[j]; int sum = prefixSum[i + secondLen] - prefixSum[i];
heights[j] = tmpHeight; if (sum >= maxRight) {
String tmpName = names[i]; maxRight = sum;
names[i] = names[j];
names[j] = tmpName;
} }
maxSumRight[i] = maxRight;
} }
int tmpHeight = heights[i + 1]; for (int i = firstLen - 1; i <= n - secondLen; i++) {
heights[i + 1] = heights[end]; int sum = prefixSum[i + 1] - prefixSum[i - firstLen + 1];
heights[end] = tmpHeight; maxSum = Math.max(maxSum, sum + maxSumRight[i + 1]);
String tmpName = names[i + 1]; maxSum = Math.max(maxSum, sum + maxSumLeft[i - 1]);
names[i + 1] = names[end]; }
names[end] = tmpName; return maxSum;
return i + 1;
} }
public static void main(String[] args) { public static void main(String[] args) {
String[] names = {"Mary", "John", "Emma"}; int[] nums1 = { 0, 6, 5, 2, 2, 5, 1, 9, 4 };
int[] heights = {180, 165, 170}; int firstLen1 = 1;
String[] sortedNames = sortByName(names, heights); int secondLen1 = 2;
System.out.println(Arrays.toString(sortedNames)); System.out.println(maxSumTwoNoOverlap(nums1, firstLen1, secondLen1)); // expect 20
} }
} }

Loading…
Cancel
Save