Untitled
import java.util.*; public class MaxScoreWithKOperations { public long maxKelements(int[] nums, int k) { // Step 1: Create a max-heap (PriorityQueue with reverse order) PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a); for (int num : nums) { maxHeap.offer(num); } // Step 2: Perform k operations long score = 0; for (int i = 0; i < k; i++) { // Extract the largest element int maxVal = maxHeap.poll(); score += maxVal; // Calculate the ceiling of maxVal / 3 and reinsert into the heap int nextVal = (maxVal + 2) / 3; maxHeap.offer(nextVal); } // Step 3: Return the total score return score; } public static void main(String[] args) { MaxScoreWithKOperations solution = new MaxScoreWithKOperations(); // Example 1 int[] nums1 = {10, 10, 10, 10, 10}; int k1 = 5; System.out.println(solution.maxKelements(nums1, k1)); // Output: 50 // Example 2 int[] nums2 = {1, 10, 3, 3, 3}; int k2 = 3; System.out.println(solution.maxKelements(nums2, k2)); // Output: 17 } }
Leave a Comment