Maximum Sum With at Most K Elements - Problem

You are given a 2D integer matrix grid of size n × 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 ith row of grid does not exceed limits[i].

Return the maximum sum.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[1,2],[3,4]], limits = [1,1], k = 2
Output: 6
💡 Note: Take the largest possible elements: 4 from row 1 and 2 from row 0 (since limit allows only 1 element per row). Sum = 4 + 2 = 6
Example 2 — Higher Limits
$ Input: grid = [[5,1],[2,3]], limits = [2,1], k = 3
Output: 10
💡 Note: Sorted elements: [5,3,2,1]. Take 5 (row 0), 3 (row 1), 2 (row 0). Sum = 5 + 3 + 2 = 10
Example 3 — Limited by k
$ Input: grid = [[10,8],[6,4]], limits = [2,2], k = 1
Output: 10
💡 Note: Even though limits allow taking more elements, k=1 limits us to just one element. Take the maximum: 10

Constraints

  • 1 ≤ n, m ≤ 100
  • 1 ≤ k ≤ n × m
  • 0 ≤ limits[i] ≤ m
  • -1000 ≤ grid[i][j] ≤ 1000

Visualization

Tap to expand
Maximum Sum With at Most K Elements INPUT Grid (2x2 matrix) 1 2 3 4 Row 0 Row 1 [0] [1] Limits Array 1 1 Row 0 Row 1 k = 2 (max elements) k = 2 Select at most 2 elements Max 1 from each row ALGORITHM STEPS 1 Collect All Elements Gather: [1, 2, 3, 4] 2 Build Max Heap Priority Queue: [4, 3, 2, 1] 4 3 2 1 3 Extract Top K Pop 4 (row1), Pop 3 (row0) 4 Check Limits Row0: 1/1 OK, Row1: 1/1 OK Sum = 4 + 3 = 7 FINAL RESULT Selected Elements 1 2 3 4 Selected! Selected! Calculation: 4 + 3 = 7 (max from each row) Maximum Sum 7 OK - Valid Solution! Key Insight: Use a Max Heap (Priority Queue) to always pick the largest available element. Track elements taken per row to respect limits. Greedy approach works because we want maximum sum. TutorialsPoint - Maximum Sum With at Most K Elements | Greedy with Priority Queue
Asked in
Google 15 Amazon 12 Microsoft 8
8.9K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen