Find K Maximum Elements
Problem Statement
You are given an integer array arr of size n and an integer k.
Your task is to find the k largest elements from the array.
The order of output does not matter unless specified.
Example
Input
arr = [1, 23, 12, 9, 30, 2, 50]
k = 3
Output
[50, 30, 23]
Why This Problem Is Important
Very common interview question
Tests sorting vs heap optimization
Introduces heap data structure
Used in top-K, ranking, analytics problems
Foundation for streaming & priority problems
Approaches Overview
| Approach | Technique | Time | Space |
|---|---|---|---|
| Approach 1 | Brute Force (Repeated Max) | O(n × k) | O(1) |
| Approach 2 | Sorting | O(n log n) | O(1) |
| Approach 3 | Min Heap of Size K | O(n log k) | O(k) |
| Approach 4 | Max Heap | O(n + k log n) | O(n) |
Approach 1: Brute Force (Repeated Maximum)
Idea
Find the maximum element k times.
After each extraction, mark the element as used.
Algorithm
- Repeat k times
- Find maximum in array
- Print/store it
- Mark it as used
Time & Space Complexity
Time: O(n × k)
Space: O(1)
This approach finds the top k largest elements by repeatedly scanning the array and marking the chosen max as -∞.
C Implementation
#include
#include
int main() {
int arr[] = {1,23,12,9,30,2,50};
int n = 7, k = 3;
for(int t = 0; t < k; t++) {
int max = INT_MIN, idx = -1;
for(int i = 0; i < n; i++) {
if(arr[i] > max) {
max = arr[i];
idx = i;
}
}
printf("%d ", max);
arr[idx] = INT_MIN;
}
return 0;
}
Output:
50 30 23
C++ Implementation
#include
#include
using namespace std;
int main() {
int arr[] = {1,23,12,9,30,2,50};
int n = 7, k = 3;
for(int t = 0; t < k; t++) {
int max = INT_MIN, idx = -1;
for(int i = 0; i < n; i++) {
if(arr[i] > max) {
max = arr[i];
idx = i;
}
}
cout << max << " ";
arr[idx] = INT_MIN;
}
return 0;
}
Output:
50 30 23
Java Implementation
public class Main {
public static void main(String[] args) {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
for(int t = 0; t < k; t++) {
int max = Integer.MIN_VALUE, idx = -1;
for(int i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i];
idx = i;
}
}
System.out.print(max + " ");
arr[idx] = Integer.MIN_VALUE;
}
}
}
Output:
50 30 23
Python Implementation
arr = [1,23,12,9,30,2,50]
k = 3
for _ in range(k):
m = max(arr)
print(m, end=" ")
arr[arr.index(m)] = float('-inf')
Output:
50 30 23
JavaScript Implementation
let arr = [1,23,12,9,30,2,50];
let k = 3;
for(let t = 0; t < k; t++) {
let max = -Infinity, idx = -1;
for(let i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i];
idx = i;
}
}
process.stdout.write(max + " ");
arr[idx] = -Infinity;
}
Output:
50 30 23
C# Implementation
using System;
class Program {
static void Main() {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
for(int t = 0; t < k; t++) {
int max = int.MinValue, idx = -1;
for(int i = 0; i < arr.Length; i++) {
if(arr[i] > max) {
max = arr[i];
idx = i;
}
}
Console.Write(max + " ");
arr[idx] = int.MinValue;
}
}
}
Output:
50 30 23
Approach 2: Sorting
Idea
Sort the array in descending order and take first k elements.
Time & Space Complexity
Time: O(n log n)
Space: O(1)
This approach sorts the array in descending order and prints the first k largest elements.
C++ Implementation
#include
#include
using namespace std;
int main() {
int arr[] = {1,23,12,9,30,2,50};
int n = 7, k = 3;
sort(arr, arr + n, greater());
for(int i = 0; i < k; i++)
cout << arr[i] << " ";
return 0;
}
Output:
50 30 23
Java Implementation
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
Arrays.sort(arr);
for(int i = arr.length - 1; i >= arr.length - k; i--)
System.out.print(arr[i] + " ");
}
}
Output:
50 30 23
Python Implementation
arr = [1,23,12,9,30,2,50]
k = 3
arr.sort(reverse=True)
print(*arr[:k])
Output:
50 30 23
JavaScript Implementation
let arr = [1,23,12,9,30,2,50];
let k = 3;
arr.sort((a,b) => b - a);
console.log(arr.slice(0, k).join(" "));
Output:
50 30 23
C# Implementation
using System;
class Program {
static void Main() {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
Array.Sort(arr);
for(int i = arr.Length - 1; i >= arr.Length - k; i--)
Console.Write(arr[i] + " ");
}
}
Output:
50 30 23
Approach 3: Min Heap of Size K (Optimal)
Idea
Maintain a min heap of size k.
If a new element is greater than heap top, replace it.
Time & Space Complexity
Time: O(n log k)
Space: O(k)
This approach uses a min-heap of size k to keep track of the k largest elements.
Given:
arr = [1, 23, 12, 9, 30, 2, 50]
k = 3
Top 3 largest elements → 50, 30, 23
Since we pop from a min-heap, output order will be:
23 30 50
C++ Implementation (Min Heap)
#include
#include
using namespace std;
int main() {
int arr[] = {1,23,12,9,30,2,50};
int n = 7, k = 3;
priority_queue, greater> pq;
for(int i = 0; i < n; i++) {
pq.push(arr[i]);
if(pq.size() > k)
pq.pop();
}
while(!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
Output:
23 30 50
Java Implementation
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
PriorityQueue pq = new PriorityQueue<>();
for(int num : arr) {
pq.add(num);
if(pq.size() > k)
pq.poll();
}
while(!pq.isEmpty())
System.out.print(pq.poll() + " ");
}
}
Output:
23 30 50
Python Implementation
import heapq
arr = [1,23,12,9,30,2,50]
k = 3
heap = []
for num in arr:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
while heap:
print(heapq.heappop(heap), end=" ")
Output:
23 30 50
JavaScript Implementation (Custom Min Heap)
class MinHeap {
constructor() {
this.heap = [];
}
push(val) {
this.heap.push(val);
this.heap.sort((a,b)=>a-b);
}
pop() {
return this.heap.shift();
}
size() {
return this.heap.length;
}
}
let arr = [1,23,12,9,30,2,50];
let k = 3;
let pq = new MinHeap();
for(let num of arr) {
pq.push(num);
if(pq.size() > k)
pq.pop();
}
while(pq.size())
process.stdout.write(pq.pop() + " ");
Output:
23 30 50
C# Implementation
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
var pq = new PriorityQueue();
foreach(int num in arr) {
pq.Enqueue(num, num);
if(pq.Count > k)
pq.Dequeue();
}
while(pq.Count > 0)
Console.Write(pq.Dequeue() + " ");
}
}
Output:
23 30 50
Approach 4: Max Heap
Idea
Build a max heap of all elements.
Extract top k times.
Time & Space Complexity
Time: O(n + k log n)
Space: O(n)
C++ Implementation
#include
#include
using namespace std;
int main() {
int arr[] = {1,23,12,9,30,2,50};
int n = 7, k = 3;
priority_queue pq;
for(int i = 0; i < n; i++)
pq.push(arr[i]);
for(int i = 0; i < k; i++) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
Output:
50 30 23
Java Implementation
import java.util.PriorityQueue;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
PriorityQueue pq =
new PriorityQueue<>(Collections.reverseOrder());
for(int num : arr)
pq.add(num);
for(int i = 0; i < k; i++)
System.out.print(pq.poll() + " ");
}
}
Output:
50 30 23
Python Implementation
import heapq
arr = [1,23,12,9,30,2,50]
k = 3
# max heap using negatives
heap = [-x for x in arr]
heapq.heapify(heap)
for _ in range(k):
print(-heapq.heappop(heap), end=" ")
Output:
50 30 23
JavaScript Implementation (Custom Max Heap via sort)
let arr = [1,23,12,9,30,2,50];
let k = 3;
arr.sort((a,b) => b - a);
for(let i = 0; i < k; i++)
process.stdout.write(arr[i] + " ");
Output:
50 30 23
C# Implementation
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int[] arr = {1,23,12,9,30,2,50};
int k = 3;
var pq = new PriorityQueue();
foreach(int num in arr)
pq.Enqueue(num, -num); // negative priority for max heap
for(int i = 0; i < k; i++)
Console.Write(pq.Dequeue() + " ");
}
}
Output:
50 30 23
Summary
- Brute force is slow
- Sorting is simple but not optimal
- Min heap of size k is best for large data
- Max heap is useful when all elements are needed later
Next Problem in the Series
Minimum Number of Jumps to Reach End
