give code for this in the format shown in image
Erstellt am: 2. September 2025
Beantwortet mit GPT-5 Thinking von Chat01
Erstellt am: 2. September 2025
Beantwortet mit GPT-5 Thinking von Chat01
give code for this in the format shown in image
Here’s a clean, efficient Java-8 solution that matches the exact function signature shown in your screenshot. Paste this inside the class Result stub.
javapublic static int getMaxLoad(List<Integer> price, List<Integer> load, int max_price) { int n = price.size(); if (n == 0) return 0; // Pack [price, load] and sort by price int[][] arr = new int[n][2]; for (int i = 0; i < n; i++) { arr[i][0] = price.get(i); arr[i][1] = load.get(i); } java.util.Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0])); // prefix[i] = maximum load among arr[0..i] int[] prefix = new int[n]; prefix[0] = arr[0][1]; for (int i = 1; i < n; i++) { prefix[i] = Math.max(prefix[i - 1], arr[i][1]); } int best = 0; for (int j = 0; j < n; j++) { // Single server choice if ((long) arr[j][0] <= (long) max_price) { best = Math.max(best, arr[j][1]); } else { // If this server alone exceeds budget, no pair with it will work either continue; } // Pair with the best earlier server whose price <= (max_price - arr[j][0]) long remaining = (long) max_price - (long) arr[j][0]; int hi = upperBoundPrice(arr, remaining) - 1; // last index with price <= remaining if (hi >= j) hi = j - 1; // cannot pair with itself if (hi >= 0) { best = Math.max(best, arr[j][1] + prefix[hi]); } } return best; } // Returns index of first element with price > val (i.e., upper_bound) private static int upperBoundPrice(int[][] arr, long val) { int l = 0, r = arr.length; while (l < r) { int m = (l + r) >>> 1; if ((long) arr[m][0] <= val) l = m + 1; else r = m; } return l; }
Idea: Sort servers by price, keep a prefix of the best load seen so far, and for each server binary-search the most expensive earlier server that still fits within the remaining budget. This handles both single-server and two-server choices in O(n log n) time.