Leetcode 3065. Minimum Operations to Exceed Threshold Value I
You are given an integer array arr and two integers threshold and maxOperations.
In one operation, you can remove one element from arr and divide it into any numbers of new elements such that their sum is equal to the removed element. The goal is to perform the minimum number of operations such that the sum of the array exceeds threshold.
Return the minimum number of operations required. If it is impossible to achieve this, return -1.
arr?arr, threshold, and maxOperations?arr is empty?threshold is less than or equal to the sum of arr already?maxOperations is 0?arr.threshold, return 0 since no operations are necessary.threshold, return the number of operations performed.maxOperations and still haven’t met the threshold, return -1.import java.util.Collections;
import java.util.PriorityQueue;
public class MinOperationsToExceedThreshold {
public int minOperations(int[] arr, int threshold, int maxOperations) {
long sum = 0;
for (int num : arr) {
sum += num;
}
if (sum >= threshold) {
return 0;
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (int num : arr) {
maxHeap.add(num);
}
int operations = 0;
while (operations < maxOperations && sum < threshold && !maxHeap.isEmpty()) {
int maxElement = maxHeap.poll();
// Since we are dividing maxElement into 2 parts, we create two new elements.
int newElement1 = maxElement / 2;
int newElement2 = maxElement - newElement1;
sum = sum - maxElement + newElement1 + newElement2;
maxHeap.add(newElement1);
maxHeap.add(newElement2);
operations++;
}
return sum >= threshold ? operations : -1;
}
public static void main(String[] args) {
MinOperationsToExceedThreshold solver = new MinOperationsToExceedThreshold();
int[] arr = {10, 20, 30};
int threshold = 60;
int maxOperations = 3;
System.out.println(solver.minOperations(arr, threshold, maxOperations)); // Output: 1
}
}
n is the length of arr.maxOperations operations.The solution is efficient given realistic constraints and handles several edge cases appropriately.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?