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.
There are an infinite amount of bags on a number line, one bag for each coordinate. Some of these bags contain coins.
You are given a 2D array coins, where coins[i] = [li, ri, ci] denotes that every bag from li to ri contains ci coins.
The segments that coins contain are non-overlapping.
You are also given an integer k.
Return the maximum amount of coins you can obtain by collecting k consecutive bags.
Example 1:
Input: coins = [[8,10,1],[1,3,2],[5,6,4]], k = 4
Output: 10
Explanation:
Selecting bags at positions [3, 4, 5, 6] gives the maximum number of coins: 2 + 0 + 4 + 4 = 10.
Example 2:
Input: coins = [[1,10,3]], k = 2
Output: 6
Explanation:
Selecting bags at positions [1, 2] gives the maximum number of coins: 3 + 3 = 6.
Constraints:
1 <= coins.length <= 1051 <= k <= 109coins[i] == [li, ri, ci]1 <= li <= ri <= 1091 <= ci <= 1000Problem summary: There are an infinite amount of bags on a number line, one bag for each coordinate. Some of these bags contain coins. You are given a 2D array coins, where coins[i] = [li, ri, ci] denotes that every bag from li to ri contains ci coins. The segments that coins contain are non-overlapping. You are also given an integer k. Return the maximum amount of coins you can obtain by collecting k consecutive bags.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Greedy · Sliding Window
[[8,10,1],[1,3,2],[5,6,4]] 4
[[1,10,3]] 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3413: Maximum Coins From K Consecutive Bags
class Solution {
public long maximumCoins(int[][] coins, int k) {
int[][] negatedCoins = negateLeftRight(coins);
return Math.max(slide(coins, k), slide(negatedCoins, k));
}
private int[][] negateLeftRight(int[][] coins) {
int[][] res = new int[coins.length][3];
for (int i = 0; i < coins.length; ++i) {
final int l = coins[i][0];
final int r = coins[i][1];
final int c = coins[i][2];
res[i][0] = -r;
res[i][1] = -l;
res[i][2] = c;
}
return res;
}
private long slide(int[][] coins, int k) {
long res = 0;
long windowSum = 0;
int j = 0;
Arrays.sort(coins, Comparator.comparingInt((int[] coin) -> coin[0]));
for (int[] coin : coins) {
final int li = coin[0];
final int ri = coin[1];
final int ci = coin[2];
final int rightBoundary = li + k;
// [lj, rj] is fully in [li..li + k).
while (j + 1 < coins.length && coins[j + 1][0] < rightBoundary) {
final int lj = coins[j][0];
final int rj = coins[j][1];
final int cj = coins[j][2];
windowSum += (long) (rj - lj + 1) * cj;
++j;
}
// [lj, rj] may be partially in [l..l + k).
long last = 0;
if (j < coins.length && coins[j][0] < rightBoundary) {
final int lj = coins[j][0];
final int rj = coins[j][1];
final int cj = coins[j][2];
last = (long) (Math.min(rightBoundary - 1, rj) - lj + 1) * cj;
}
res = Math.max(res, windowSum + last);
windowSum -= (long) (ri - li + 1) * ci;
}
return res;
}
}
// Accepted solution for LeetCode #3413: Maximum Coins From K Consecutive Bags
package main
import "slices"
// https://space.bilibili.com/206214
// 2271. 毯子覆盖的最多白色砖块数
func maximumWhiteTiles(tiles [][]int, carpetLen int) (ans int) {
cover, left := 0, 0
for _, tile := range tiles {
tl, tr, c := tile[0], tile[1], tile[2]
cover += (tr - tl + 1) * c
carpetLeft := tr - carpetLen + 1
for tiles[left][1] < carpetLeft {
cover -= (tiles[left][1] - tiles[left][0] + 1) * tiles[left][2]
left++
}
uncover := max((carpetLeft-tiles[left][0])*tiles[left][2], 0)
ans = max(ans, cover-uncover)
}
return
}
func maximumCoins(coins [][]int, k int) int64 {
slices.SortFunc(coins, func(a, b []int) int { return a[0] - b[0] })
ans := maximumWhiteTiles(coins, k)
slices.Reverse(coins)
for _, t := range coins {
t[0], t[1] = -t[1], -t[0]
}
return int64(max(ans, maximumWhiteTiles(coins, k)))
}
# Accepted solution for LeetCode #3413: Maximum Coins From K Consecutive Bags
class Solution:
def maximumCoins(self, coins: list[list[int]], k: int) -> int:
return max(self._slide(coins, k),
self._slide([[-r, -l, c] for l, r, c in coins], k))
def _slide(self, coins: list[list[int]], k: int) -> int:
coins.sort()
res = 0
windowSum = 0
j = 0
for li, ri, ci in coins: # Consider the number line [li..li + k).
rightBoundary = li + k
# [lj, rj] is fully in [li..li + k).
while j + 1 < len(coins) and coins[j + 1][0] < rightBoundary:
lj, rj, cj = coins[j]
windowSum += (rj - lj + 1) * cj
j += 1
# [lj, rj] may be partially in [l..l + k).
last = 0
if j < len(coins) and coins[j][0] < rightBoundary:
lj, rj, cj = coins[j]
last = (min(rightBoundary - 1, rj) - lj + 1) * cj
res = max(res, windowSum + last)
windowSum -= (ri - li + 1) * ci
return res
// Accepted solution for LeetCode #3413: Maximum Coins From K Consecutive Bags
// 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 #3413: Maximum Coins From K Consecutive Bags
// class Solution {
// public long maximumCoins(int[][] coins, int k) {
// int[][] negatedCoins = negateLeftRight(coins);
// return Math.max(slide(coins, k), slide(negatedCoins, k));
// }
//
// private int[][] negateLeftRight(int[][] coins) {
// int[][] res = new int[coins.length][3];
// for (int i = 0; i < coins.length; ++i) {
// final int l = coins[i][0];
// final int r = coins[i][1];
// final int c = coins[i][2];
// res[i][0] = -r;
// res[i][1] = -l;
// res[i][2] = c;
// }
// return res;
// }
//
// private long slide(int[][] coins, int k) {
// long res = 0;
// long windowSum = 0;
// int j = 0;
//
// Arrays.sort(coins, Comparator.comparingInt((int[] coin) -> coin[0]));
//
// for (int[] coin : coins) {
// final int li = coin[0];
// final int ri = coin[1];
// final int ci = coin[2];
// final int rightBoundary = li + k;
//
// // [lj, rj] is fully in [li..li + k).
// while (j + 1 < coins.length && coins[j + 1][0] < rightBoundary) {
// final int lj = coins[j][0];
// final int rj = coins[j][1];
// final int cj = coins[j][2];
// windowSum += (long) (rj - lj + 1) * cj;
// ++j;
// }
//
// // [lj, rj] may be partially in [l..l + k).
// long last = 0;
// if (j < coins.length && coins[j][0] < rightBoundary) {
// final int lj = coins[j][0];
// final int rj = coins[j][1];
// final int cj = coins[j][2];
// last = (long) (Math.min(rightBoundary - 1, rj) - lj + 1) * cj;
// }
//
// res = Math.max(res, windowSum + last);
// windowSum -= (long) (ri - li + 1) * ci;
// }
//
// return res;
// }
// }
// Accepted solution for LeetCode #3413: Maximum Coins From K Consecutive Bags
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3413: Maximum Coins From K Consecutive Bags
// class Solution {
// public long maximumCoins(int[][] coins, int k) {
// int[][] negatedCoins = negateLeftRight(coins);
// return Math.max(slide(coins, k), slide(negatedCoins, k));
// }
//
// private int[][] negateLeftRight(int[][] coins) {
// int[][] res = new int[coins.length][3];
// for (int i = 0; i < coins.length; ++i) {
// final int l = coins[i][0];
// final int r = coins[i][1];
// final int c = coins[i][2];
// res[i][0] = -r;
// res[i][1] = -l;
// res[i][2] = c;
// }
// return res;
// }
//
// private long slide(int[][] coins, int k) {
// long res = 0;
// long windowSum = 0;
// int j = 0;
//
// Arrays.sort(coins, Comparator.comparingInt((int[] coin) -> coin[0]));
//
// for (int[] coin : coins) {
// final int li = coin[0];
// final int ri = coin[1];
// final int ci = coin[2];
// final int rightBoundary = li + k;
//
// // [lj, rj] is fully in [li..li + k).
// while (j + 1 < coins.length && coins[j + 1][0] < rightBoundary) {
// final int lj = coins[j][0];
// final int rj = coins[j][1];
// final int cj = coins[j][2];
// windowSum += (long) (rj - lj + 1) * cj;
// ++j;
// }
//
// // [lj, rj] may be partially in [l..l + k).
// long last = 0;
// if (j < coins.length && coins[j][0] < rightBoundary) {
// final int lj = coins[j][0];
// final int rj = coins[j][1];
// final int cj = coins[j][2];
// last = (long) (Math.min(rightBoundary - 1, rj) - lj + 1) * cj;
// }
//
// res = Math.max(res, windowSum + last);
// windowSum -= (long) (ri - li + 1) * ci;
// }
//
// return res;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
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: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
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.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.