Priority Queue Sum Top K
Published at25 Jul 2026
Created by M Ichsanul Fadhil
Given an array and k, return the sum of the top k largest elements. Sort descending, take the first k, and sum them. Return -1 if k exceeds array length.
Example Input & Output
Example 1
Input
[5],1
Output
5
Explanation
Single
Example 2
Input
[1,2],5
Output
-1
Explanation
k > n
Example 3
Input
[1,2,3,4,5],3
Output
12
Explanation
Top 3 sum = 5+4+3=12
Example 4
Input
[10,5,7,2],2
Output
17
Explanation
Top 2 sum = 10+7=17
Example 5
Input
[],3
Output
-1
Explanation
Empty
Algorithm Flow

Recommendation Algorithm Flow for Priority Queue Sum Top K
Solution Approach
Best Answers
java
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.
