#3462
Maximum Sum With at Most K Elements
MediumArrayGreedySortingHeap (Priority Queue)MatrixGreedyHeap
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m log m + k log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m log m + k log k)Space O(n)
By sorting each row and using a max-heap, we can efficiently select the largest elements while respecting the limits and the total count k.
⚙️
Algorithm
3 steps- 1Step 1: Sort each row of the grid in descending order.
- 2Step 2: Use a max-heap to collect the largest elements up to the limits specified.
- 3Step 3: Extract the top k elements from the heap to compute the maximum sum.
solution.py9 lines
1import heapq
2
3def maxSum(grid, limits, k):
4 max_heap = []
5 for row, limit in zip(grid, limits):
6 row.sort(reverse=True)
7 for num in row[:limit]:
8 heapq.heappush(max_heap, num)
9 return sum(heapq.nlargest(k, max_heap))ℹ
Complexity note: Sorting each row takes O(m log m) and extracting k elements from the heap takes O(k log k).
- 1Sorting helps in quickly accessing the largest elements.
- 2Using a max-heap allows efficient retrieval of the top k elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.