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 ofgriddoes not exceedlimits[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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code