BackeasyGreedyGoogleAmazon

Node Matrix Analyzer 46 Solution

Problem Statement

You are given an integer array nums and an integer K. Your task is to compute the sum of the K greatest values present in nums. The array may contain positive, zero, or negative numbers, and K will always be a valid count (1 ≤ K ≤ nums.length). Return the resulting sum as a single integer.

Input Format:

  • The first line contains two space‑separated integers N (the size of the array) and K.
  • The second line contains N space‑separated integers representing the elements of nums.

Output Format:

  • Output a single integer—the sum of the K largest elements in the array.

Your solution should run efficiently for large N, preferably in O(N log K) time or better.

Example 1
Input
5 2 3 1 9 7 5
Output
16

Explanation: The array is [3, 1, 9, 7, 5] and K = 2. Sorting or selecting the two biggest numbers gives 9 and 7. Their sum is 9 + 7 = 16.

Example 2
Input
6 3 -2 -1 0 4 3 2
Output
9

Explanation: The three largest values are 4, 3 and 2. Adding them yields 4 + 3 + 2 = 9.

Example 3
Input
4 4 10 -5 7 2
Output
14

Explanation: K equals the array length, so all elements are included. 10 + (-5) + 7 + 2 = 14.

Constraints

  • 1 ≤ N ≤ 10^5
  • 1 ≤ K ≤ N
  • -10^9 ≤ nums[i] ≤ 10^9
  • The sum fits within a 64‑bit signed integer.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Node Matrix Analyzer 46 — Problem Statement & Solution Guide

GreedyEasyFrequency Hash Map
TimeO(N log K)
|
SpaceO(K)

Problem Description

You are given an integer array nums and an integer K. Your task is to compute the sum of the K greatest values present in nums. The array may contain positive, zero, or negative numbers, and K will always be a valid count (1 ≤ K ≤ nums.length). Return the resulting sum as a single integer.

Input Format:

- The first line contains two space‑separated integers N (the size of the array) and K.

- The second line contains N space‑separated integers representing the elements of nums.

Output Format:

- Output a single integer—the sum of the K largest elements in the array.

Your solution should run efficiently for large N, preferably in O(N log K) time or better.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Node Matrix Analyzer 46"

easy

WHY DOES IT MATTER?

Selecting top‑K items appears in ranking, recommendation, and resource allocation systems.

OPTIMIZATION CHALLENGE

The key is to avoid sorting the whole dataset and limit extra memory to K.

REAL-WORLD CONNECTION

Think of a streaming service keeping the K most‑watched movies in real time.

Initialize a min‑heap, push first K numbers, then stream remaining values, swapping only when beneficial.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log K)
💾 Space:O(K)

Core Theory — Why This Approach?

The task reduces to selecting the K largest elements from an unsorted list, which is a classic selection problem. A naive full sort costs O(N log N), but the greedy insight that only the top K matter enables linear‑time selection via a min‑heap of size K or Quickselect partitioning, dramatically reducing work on large N. Naïve approaches like scanning the array K times or repeatedly removing the max are O(K·N) and become prohibitive when N is large. The optimal paradigm leverages a bounded priority queue (min‑heap) to maintain the current K best values while iterating once, guaranteeing O(N log K) time and O(K) extra space, which is optimal for arbitrary input distributions.

Interview Questions on This Problem

Q1Why is sorting the entire array suboptimal for this problem?

Sorting costs O(N log N) even though we only need K elements. A heap or Quickselect can achieve O(N log K) or O(N) expected time.

Q2How does a min‑heap of size K help maintain the K greatest values?

The heap stores the current K largest; the smallest among them sits at the root. When a new element exceeds the root, we replace it, keeping only the top K.

Q3Can you solve this problem in O(N) worst‑case time?

Yes, using the deterministic linear‑time selection algorithm (Median‑of‑Medians) to find the K‑th largest pivot, then summing all elements above it. However, the heap solution is simpler and fast in practice.

Examples

Example 1

Input

5 2
3 1 9 7 5

Output

16

Explanation: The array is [3, 1, 9, 7, 5] and K = 2. Sorting or selecting the two biggest numbers gives 9 and 7. Their sum is 9 + 7 = 16.

Example 2

Input

6 3
-2 -1 0 4 3 2

Output

9

Explanation: The three largest values are 4, 3 and 2. Adding them yields 4 + 3 + 2 = 9.

Example 3

Input

4 4
10 -5 7 2

Output

14

Explanation: K equals the array length, so all elements are included. 10 + (-5) + 7 + 2 = 14.

Constraints

  • 1 ≤ N ≤ 10^5
  • 1 ≤ K ≤ N
  • -10^9 ≤ nums[i] ≤ 10^9
  • The sum fits within a 64‑bit signed integer.

Optimal Approach & Strategy

Use a min‑heap of capacity K to keep only the top K values during a single pass.

Brute Force Approach

Sort the entire array descending and sum the first K elements.

Verified Code Solutions

JavaScript Solution
Time: O(N log K)
function solution(nums, k) {
   nums.sort((a, b) => b - a);
   let sum = 0;
   for (let i = 0; i < k; i++) {
       sum += nums[i];
   }
   return sum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.