Priority Queue Sum Top K
Given an array of integers and an integer k, find the sum of the k largest elements in the array. Identify the top k values, add them together, and return the total. If k is greater than the array length, or the array is empty, return -1.
For example, in the array [10, 5, 7, 2] with k=2, the two largest elements are 10 and 7, and their sum is 17. In [1, 2, 3, 4, 5] with k=3, the top three are 5, 4, and 3, giving a sum of 12. With k=1, the sum is just the maximum element. If k exceeds the array length, like [1, 2] with k=5, return -1. An empty array with any k also returns -1.
Summing the top k elements is a practical aggregation used in leaderboards (total points of the top scorers), financial reporting (revenue from the top contributors), and resource allocation (highest-demand items). It requires first isolating the k most significant values before summing them.
The most straightforward approach sorts the array in descending order and sums the first k elements. This runs in O(n log n) time. Before sorting, check whether k is valid: if k exceeds the array length or the array is empty, return -1 immediately. For large arrays where k is much smaller than n, a min-heap of size k can maintain the k largest values in O(n log k) time.
Edge cases include k=1 (return the maximum element), k equal to the array length (return the sum of all elements), k greater than the array length (return -1), and an empty array (return -1).
Example Input & Output
Single
k > n
Top 3 sum = 5+4+3=12
Top 2 sum = 10+7=17
Empty
Algorithm Flow
Solution Approach
Check that k is valid (k must not exceed the array length and the array must not be empty — otherwise return -1). Then sort a copy of the array in descending order and sum the first k elements.
Sorting descending places the largest values first. Summing the first k of them gives the required total. A min-heap of size k would achieve O(n log k) instead of O(n log n) for very large arrays.
Time O(n log n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] nums, int k) {
if(k>nums.length)return -1;int[] s=nums.clone();Arrays.sort(s);int sum=0;
for(int i=0;i<k;i++)sum+=s[nums.length-1-i];
return sum;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
