Problem Description
Given an n x m integer matrix grid, an array limits of length n where limits[i] represents the maximum number of elements that can be taken from the iᵗʰ row, and an integer k, the task is to compute the maximum sum you can obtain by selecting at most k elements in total from the grid. For each row, you cannot select more than limits[i] elements.
Key Insights
- You want the maximum total sum, so picking high-value elements is ideal.
- For each row, sort the elements in descending order so that the best candidates appear first.
- Compute prefix sums for each row to quickly calculate the total sum when picking a certain number of highest elements from that row.
- Use dynamic programming (DP) where dp[j] represents the maximum sum achievable with exactly j elements selected overall.
- Process each row and update the DP array in reverse order to avoid interfering with the current row’s transition (similar to the knapsack problem).
Space and Time Complexity
Time Complexity: O(n * m log m + n * k * min(m, limits[i])) Space Complexity: O(k), plus O(m) extra space per row when computing sorted order and prefix sums.
Solution
The approach is to treat the problem like a knapsack DP. For each row, sort the row in descending order and compute its prefix sums. For every valid count of elements we might select from the row (up to limits[i]), we update a DP array that tracks the maximum sum achievable with a given total number of selected elements. The key is to update the DP state in reverse (from k downwards) to ensure each row’s choices are only counted once per iteration.