Imagine you're a treasure hunter with a magical bag that can hold at most k precious gems. You've discovered an ancient temple with a grid of gem chambers, where each chamber contains gems of different values.
However, there's a catch! Each row of chambers has a guardian that limits how many gems you can take from that row. The i-th row's guardian allows you to take at most limits[i] gems from that entire row.
Your mission: Select at most k gems from the entire grid to maximize their total value, while respecting each row's guardian limits.
Input:
• A 2D matrix grid of size n × m containing gem values
• An array limits of length n specifying max gems per row
• An integer k representing your bag capacity
Output: The maximum possible sum of gem values you can collect.
Input & Output
Constraints
- 1 ≤ n, m ≤ 103
- 1 ≤ grid[i][j] ≤ 104
- 0 ≤ limits[i] ≤ m
- 1 ≤ k ≤ n × m
- Sum of all limits[i] ≥ k is not guaranteed