LeetCode #3413 — MEDIUM

Maximum Coins From K Consecutive Bags

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

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 <= 105
  • 1 <= k <= 109
  • coins[i] == [li, ri, ci]
  • 1 <= li <= ri <= 109
  • 1 <= ci <= 1000
  • The given segments are non-overlapping.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Binary Search · Greedy · Sliding Window

Example 1

[[8,10,1],[1,3,2],[5,6,4]]
4

Example 2

[[1,10,3]]
2
Step 02

Core Insight

What unlocks the optimal approach

  • An optimal starting position for <code>k</code> consecutive bags will be either <code>l<sub>i</sub></code> or <code>r<sub>i</sub> - k + 1</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

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;
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

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.

BINARY SEARCH
O(log n) time
O(1) space

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).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

Boundary update without `+1` / `-1`

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.

Using greedy without proof

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.

Shrinking the window only once

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.