Untitled

 avatar
unknown
plain_text
14 days ago
1.2 kB
0
Indexable
import java.util.PriorityQueue;

public class KthLargestSubarraySum {
    public static int findKthLargestSum(int[] arr, int k) {
        // Min-heap to store the k largest sums
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();

        int n = arr.length;

        // Generate all subarray sums
        for (int i = 0; i < n; i++) {
            int currentSum = 0;

            for (int j = i; j < n; j++) {
                currentSum += arr[j];

                // Add the current sum to the heap
                minHeap.add(currentSum);

                // Ensure heap size does not exceed k
                if (minHeap.size() > k) {
                    minHeap.poll(); // Remove the smallest element
                }
            }
        }

        // The root of the heap is the k-th largest sum
        return minHeap.peek();
    }

    public static void main(String[] args) {
        int[] arr1 = {3, 2, 1};
        int k1 = 2;
        System.out.println(findKthLargestSum(arr1, k1)); // Output: 5

        int[] arr2 = {2, 6, 4, 1};
        int k2 = 3;
        System.out.println(findKthLargestSum(arr2, k2)); // Output: 11
    }
}
Leave a Comment