Maximum Coins From K Consecutive Bags - Problem

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] = [l_i, r_i, c_i] denotes that every bag from l_i to r_i (inclusive) contains c_i 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.

Input & Output

Example 1 — Basic Case
$ Input: coins = [[1,5,10], [6,7,1], [8,10,3]], k = 4
Output: 40
💡 Note: The best 4 consecutive bags are positions 1-4, each containing 10 coins: 10 + 10 + 10 + 10 = 40 coins
Example 2 — Single Segment
$ Input: coins = [[1,3,5]], k = 2
Output: 10
💡 Note: Any 2 consecutive bags within the segment give 5 + 5 = 10 coins
Example 3 — Cross Multiple Segments
$ Input: coins = [[1,2,1], [4,5,3]], k = 3
Output: 4
💡 Note: Best window spans positions 3-5: bag 3 has 0 coins (no segment covers it), bag 4 has 3 coins, bag 5 has 3 coins = 6 total

Constraints

  • 1 ≤ coins.length ≤ 105
  • 1 ≤ li ≤ ri ≤ 105
  • 1 ≤ ci ≤ 1000
  • 1 ≤ k ≤ 2 × 105
  • The segments are non-overlapping

Visualization

Tap to expand
Maximum Coins From K Consecutive Bags INPUT Number Line with Bags [1,5] c=10 [6,7] c=1 [8,10] c=3 1 5 6 7 8 10 coins array: [[1,5,10],[6,7,1],[8,10,3]] k = 4 k = 4 Window of 4 consecutive bags Sliding Window ALGORITHM STEPS 1 Coordinate Compression Extract unique endpoints [1,5,6,7,8,10] 2 Build Prefix Sums Cumulative coins at each point pos: 1 5 6 7 8 10 sum: 10 50 51 52 55 64 (coins accumulated) 3 Sliding Window Try window starting at each pos Window [2,5]: 10*4 = 40 Window [5,8]: 10+1+1+3 = 15 Best: [2,5] = 40 coins 4 Track Maximum Update max at each position max_coins = 40 FINAL RESULT Optimal Window Position 2 3 4 5 k=4 bags 10 10 10 10 Calculation: 10 + 10 + 10 + 10 = 40 coins OUTPUT 40 OK - Maximum coins found! Window at positions [2,5] Key Insight: Coordinate Compression reduces the problem from infinite positions to just the segment endpoints. The sliding window only needs to consider starting points at compressed coordinates. For each window position, we calculate coins using prefix sums in O(1) time. TutorialsPoint - Maximum Coins From K Consecutive Bags | Coordinate Compression + Sliding Window
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen