Untitled
unknown
plain_text
10 months ago
1.1 kB
3
Indexable
import java.util.*;
class Solution {
public int[] minOperations(int[] nums, int[] queries) {
Arrays.sort(nums);
int n = nums.length;
// Compute prefix sums
long[] prefixSum = new long[n + 1];
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + nums[i];
}
int[] result = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
int q = queries[i];
// Binary search to find the position where `q` would fit
int pos = Arrays.binarySearch(nums, q);
if (pos < 0) {
pos = -(pos + 1);
}
// Left part: All elements < q
long leftCost = (long) q * pos - prefixSum[pos];
// Right part: All elements >= q
long rightCost = (prefixSum[n] - prefixSum[pos]) - (long) q * (n - pos);
// Total cost
result[i] = (int) (leftCost + rightCost);
}
return result;
}
}
Editor is loading...
Leave a Comment