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:
7
💡 Note:
Take the largest element from each row: 4 from row 1 and 3 from row 1 is not allowed due to limit. So take 4 from row 1 and 2 from row 0. Sum = 4 + 2 = 6. Actually, we can take both 4 and 3 from row 1 since limit is 1 per row. Wait - we can take 4 from row 1 (limit allows 1), then next largest is 3 from row 1 but we've used our limit for row 1. Next is 2 from row 0 (limit allows 1). Sum = 4 + 2 = 6. Actually, let me recalculate: sorted elements are [4,3,2,1], we can take 4 (row 1, count=1), then 3 (row 1 but count already 1, so skip), then 2 (row 0, count=1). So sum = 4 + 2 = 6. But wait, maybe limits allow more than 1? Let me assume limits=[1,1] means max 1 from each row. Then optimal is 4+2=6. But if limits=[2,2], then we could take 4+3=7.
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
Understanding the Visualization
1
Input
2D grid with row limits and k constraint
2
Process
Sort elements by value and greedily select
3
Output
Maximum possible sum
Key Takeaway
🎯 Key Insight: Greedy selection of largest elements while tracking row usage leads to optimal solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code