Maximum Sum With at Most K Elements Problem
#3462
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3462.
You are given a 2D integer matrix grid of size n x m, an integer array limits of length n, and an integer k. The task is to find the maximum sum of at most k elements from the matrix grid such that:
- The number of elements taken from the
i^throw ofgriddoes not exceedlimits[i].
Return the maximum sum.
Example 1:
Input: grid = [[1,2],[3,4]], limits = [1,2], k = 2
Output: 7
Explanation:
- From the second row, we can take at most 2 elements. The elements taken are 4 and 3.
- The maximum possible sum of at most 2 selected elements is 4 + 3 = 7.
Example 2:
Input: grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3
Output: 21
Explanation:
- From the first row, we can take at most 2 elements. The element taken is 7.
- From the second row, we can take at most 2 elements. The elements taken are 8 and 6.
- The maximum possible sum of at most 3 selected elements is 7 + 8 + 6 = 21.
Constraints:
n == grid.length == limits.lengthm == grid[i].length1 <= n, m <= 5000 <= grid[i][j] <= 10^50 <= limits[i] <= m0 <= k <= min(n * m, sum(limits))
Solution
Approach: Greedy + Min-Heap
Only the largest limits[i] values of row i can ever be used, and the final answer is simply the k largest values among all those candidates.
Sort each row, push its limits[i] largest values into a min-heap and pop the smallest whenever the heap grows beyond k. What remains in the heap is the best choice; add it up.
Complexity: O(nm(log m + log k)) time, O(k) extra space, where n and m are the numbers of rows and columns of grid.
from heapq import heappush, heappop
class Solution:
def maxSum(self, grid: List[List[int]], limits: List[int], k: int) -> int:
pq = []
for nums, limit in zip(grid, limits):
nums.sort()
for _ in range(limit):
heappush(pq, nums.pop())
if len(pq) > k:
heappop(pq)
return sum(pq)