Untitled
import java.util.PriorityQueue; public class MinOperationsToReduceSum { public int halveArray(int[] nums) { // Priority queue to act as a max-heap PriorityQueue<Double> maxHeap = new PriorityQueue<>((a, b) -> Double.compare(b, a)); // Calculate the initial total sum double totalSum = 0; for (int num : nums) { totalSum += num; maxHeap.offer((double) num); // Add to heap as double } double reducedSum = 0; int operations = 0; double target = totalSum / 2; // Reduce sum until reducedSum >= target while (reducedSum < target) { double largest = maxHeap.poll(); // Remove the largest number reducedSum += largest / 2; // Add half of it to the reduced sum maxHeap.offer(largest / 2); // Push the reduced number back into the heap operations++; // Increment operation count } return operations; } public static void main(String[] args) { MinOperationsToReduceSum solver = new MinOperationsToReduceSum(); int[] nums1 = {5, 19, 8, 1}; System.out.println(solver.halveArray(nums1)); // Output: 3 int[] nums2 = {3, 8, 20}; System.out.println(solver.halveArray(nums2)); // Output: 3 } }
Leave a Comment