Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a 2D integer matrix grid of size n x 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.
Example 1:
Input: grid = [[1,2],[3,4]], limits = [1,2], k = 2
Output: 7
Explanation:
4 + 3 = 7.Example 2:
Input: grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3
Output: 21
Explanation:
7 + 8 + 6 = 21.Constraints:
n == grid.length == limits.lengthm == grid[i].length1 <= n, m <= 5000 <= grid[i][j] <= 1050 <= limits[i] <= m0 <= k <= min(n * m, sum(limits))Problem summary: You are given a 2D integer matrix grid of size n x 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[[1,2],[3,4]] [1,2] 2
[[5,3,7],[8,2,6]] [2,2] 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3462: Maximum Sum With at Most K Elements
class Solution {
public long maxSum(int[][] grid, int[] limits, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
int n = grid.length;
for (int i = 0; i < n; ++i) {
int[] nums = grid[i];
int limit = limits[i];
Arrays.sort(nums);
for (int j = 0; j < limit; ++j) {
pq.offer(nums[nums.length - j - 1]);
if (pq.size() > k) {
pq.poll();
}
}
}
long ans = 0;
for (int x : pq) {
ans += x;
}
return ans;
}
}
// Accepted solution for LeetCode #3462: Maximum Sum With at Most K Elements
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func maxSum(grid [][]int, limits []int, k int) int64 {
pq := &MinHeap{}
heap.Init(pq)
n := len(grid)
for i := 0; i < n; i++ {
nums := make([]int, len(grid[i]))
copy(nums, grid[i])
limit := limits[i]
sort.Ints(nums)
for j := 0; j < limit; j++ {
heap.Push(pq, nums[len(nums)-j-1])
if pq.Len() > k {
heap.Pop(pq)
}
}
}
var ans int64 = 0
for pq.Len() > 0 {
ans += int64(heap.Pop(pq).(int))
}
return ans
}
# Accepted solution for LeetCode #3462: Maximum Sum With at Most K Elements
class Solution:
def maxSum(self, grid: List[List[int]], limits: List[int], k: int) -> int:
pq = []
for nums, limit in zip(grid, limits):
nums.sort()
for _ in range(limit):
heappush(pq, nums.pop())
if len(pq) > k:
heappop(pq)
return sum(pq)
// Accepted solution for LeetCode #3462: Maximum Sum With at Most K Elements
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3462: Maximum Sum With at Most K Elements
// class Solution {
// public long maxSum(int[][] grid, int[] limits, int k) {
// PriorityQueue<Integer> pq = new PriorityQueue<>();
// int n = grid.length;
// for (int i = 0; i < n; ++i) {
// int[] nums = grid[i];
// int limit = limits[i];
// Arrays.sort(nums);
// for (int j = 0; j < limit; ++j) {
// pq.offer(nums[nums.length - j - 1]);
// if (pq.size() > k) {
// pq.poll();
// }
// }
// }
// long ans = 0;
// for (int x : pq) {
// ans += x;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3462: Maximum Sum With at Most K Elements
function maxSum(grid: number[][], limits: number[], k: number): number {
const pq = new MinPriorityQueue<number>();
const n = grid.length;
for (let i = 0; i < n; i++) {
const nums = grid[i];
const limit = limits[i];
nums.sort((a, b) => a - b);
for (let j = 0; j < limit; j++) {
pq.enqueue(nums[nums.length - j - 1]);
if (pq.size() > k) {
pq.dequeue();
}
}
}
let ans = 0;
while (!pq.isEmpty()) {
ans += pq.dequeue();
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.