#2656
Maximum Sum With Exactly K Elements
EasyArrayGreedyGreedyHeapPriority Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + k log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + k log n)Space O(n)
The optimal approach uses a max-heap (or priority queue) to efficiently retrieve the maximum element in each iteration. This allows us to perform the operation in logarithmic time, leading to a significant reduction in overall complexity.
⚙️
Algorithm
3 steps- 1Step 1: Create a max-heap from the `nums` array.
- 2Step 2: Initialize a variable `score` to 0.
- 3Step 3: For `k` iterations, extract the maximum element from the heap, add it to `score`, and insert `max + 1` back into the heap.
solution.py12 lines
1# Full working Python code
2import heapq
3
4def maxSumOptimal(nums, k):
5 max_heap = [-num for num in nums] # Negate for max-heap
6 heapq.heapify(max_heap)
7 score = 0
8 for _ in range(k):
9 max_num = -heapq.heappop(max_heap)
10 score += max_num
11 heapq.heappush(max_heap, -(max_num + 1))
12 return scoreℹ
Complexity note: The complexity is O(n + k log n) because we first build the max-heap in O(n) time, and then each of the k operations (extract and insert) takes O(log n) time, leading to a total of O(k log n).
- 1Choosing the maximum element at each step maximizes the score.
- 2Using a max-heap allows efficient retrieval and updating of the maximum element.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.