DevPath

← All problems

Sum of the K Largest Elements

Easy heap · arrays

Description

Return the sum of the k largest elements.

Constraints

1 <= k <= n <= 100000

Examples

Input: nums = [1,4,2,3,5], k = 2

Output: 9

Hints (1)
  • Sort descending and sum the first k.

Solutions

Sort descending and sum. (requires "sort") · Time O(n log n) · Space O(1)

func sumLargestK(nums []int, k int) int {
    sort.Sort(sort.Reverse(sort.IntSlice(nums)))
    sum := 0
    for i := 0; i < k; i++ {
        sum += nums[i]
    }
    return sum
}

Create a free account to submit solutions, track progress and save problems.

Create account