Code Logo

Priority Queue Sum Top K

Published at25 Jul 2026
Priority Queue Easy 2 views
Like0

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

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

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.

function solution(arr, k) {
  if (k > arr.length || arr.length === 0) return -1;
  var sorted = arr.slice().sort(function(a, b) { return b - a; });
  var sum = 0;
  for (var i = 0; i < k; i++) sum += sorted[i];
  return sum;
}

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

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;
    }
}