Untitled

 avatar
unknown
plain_text
21 days ago
1.2 kB
2
Indexable
import java.util.PriorityQueue;
import java.util.Collections;

public class SumBetweenK1K2MaxHeap {
    public static int sumBetweenK1AndK2(int[] arr, int K1, int K2) {
        // Step 1: Create a max-heap with limited size (K2 - 1)
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

        // Step 2: Add elements to the max-heap
        for (int num : arr) {
            maxHeap.offer(num);
            if (maxHeap.size() > K2 - 1) {
                maxHeap.poll(); // Keep the size of the heap to (K2 - 1)
            }
        }

        // Step 3: Remove elements until the heap size equals (K2 - K1)
        int sum = 0;
        for (int i = K2 - 1; i > K1; i--) {
            sum += maxHeap.poll();
        }

        return sum;
    }

    public static void main(String[] args) {
        // Example 1
        int[] arr1 = {20, 8, 22, 4, 12, 10, 14};
        int K1_1 = 3, K2_1 = 6;
        System.out.println(sumBetweenK1AndK2(arr1, K1_1, K2_1)); // Output: 26

        // Example 2
        int[] arr2 = {10, 2, 50, 12, 48, 13};
        int K1_2 = 2, K2_2 = 6;
        System.out.println(sumBetweenK1AndK2(arr2, K1_2, K2_2)); // Output: 73
    }
}
Leave a Comment