Skip to main content

Maximum Coins From K Consecutive Bags - Solution & Explanation

MediumArrayBinary SearchGreedySliding Window3 min readAsked at: Amazon, Google
Practice this 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.

Approach Overview

Problem Overview: You are given ranges of bags where each bag in the range contains a certain number of coins. The task is to choose exactly k consecutive bag indices and collect the maximum total coins possible. Since ranges can overlap and bag indices can be large, the challenge is computing the maximum sum efficiently without iterating every bag index.

Approach 1: Brute Force Range Simulation (High Complexity)

The direct idea is to simulate the number of coins in every bag, then evaluate every window of length k. Build an array representing coins per bag by expanding each range and accumulating contributions. After that, iterate through all possible windows and track the maximum sum. This works conceptually but fails when bag indices are large because the array size becomes impractical. Time complexity is O(N * range + M) where M is the maximum bag index, and space complexity is O(M). This approach mainly helps understand the structure of the problem.

Approach 2: Prefix Sum on Compressed Coordinates (O(n log n))

Instead of expanding every bag index, compress the coordinates of all relevant boundaries. Convert ranges into events and compute coin contributions using a prefix sum. After building the cumulative coins for each compressed segment, evaluate the total coins inside any window of length k. This reduces memory usage dramatically because you only track meaningful breakpoints. Time complexity becomes O(n log n) due to sorting and coordinate compression, with O(n) extra space.

Approach 3: Sorting + Sliding Window on Intervals (Optimal)

The efficient solution works directly on the interval representation. First sort the coin ranges by starting index using standard sorting. Then treat the chosen segment [x, x + k - 1] as a window and compute how much each interval contributes based on overlap length. Use a sliding window with two pointers to maintain intervals intersecting the current window while adjusting contributions when the window shifts. Prefix sums or partial overlap calculations ensure each interval is processed once. Sorting dominates the runtime, giving O(n log n) time and O(n) space.

Recommended for interviews: Interviewers expect the interval-based sliding window solution. Starting with the brute force approach shows you understand the problem constraints, but recognizing that bag indices can be large leads naturally to sorting ranges and computing overlaps. Using sliding window with prefix-style accumulation demonstrates strong knowledge of interval processing and optimization techniques.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Bag SimulationO(N * range)O(M)Useful only for understanding the problem or when bag indices are very small
Coordinate Compression + Prefix SumO(n log n)O(n)When bag indices are large but the number of ranges is moderate
Sorting + Sliding Window on IntervalsO(n log n)O(n)Best general solution for interview settings and competitive programming

Video Solution

3413. Maximum Coins From K Consecutive Bags | Sliding Interval Hard • Aryan Mittal • 5,651 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Maximum Coins From K Consecutive Bags easy or hard?
Maximum Coins From K Consecutive Bags is generally classified as a Medium problem. The main difficulty is recognizing that bag indices can be large and ranges overlap, which requires interval processing with sorting and sliding window instead of direct simulation.
Maximum Coins From K Consecutive Bags Python/Java solution
Implementations typically sort the interval list, then iterate with two pointers representing the active window. Each step calculates the overlap between the window [x, x + k - 1] and existing intervals. The same logic translates directly to Python, Java, C++, or Go.
How to solve Maximum Coins From K Consecutive Bags in O(n)?
Pure O(n) is difficult because interval ranges must usually be sorted by starting index first. After sorting, a sliding window processes intervals almost linearly. The effective runtime becomes O(n log n) dominated by sorting, with near O(n) processing afterward.
What is the best approach for Maximum Coins From K Consecutive Bags?
The best approach sorts the intervals and evaluates overlaps with a sliding window of length k. Each interval contributes coins proportional to the overlap with the current window. Sorting plus incremental overlap computation keeps the algorithm efficient with O(n log n) time and O(n) space.
Is Maximum Coins From K Consecutive Bags asked at Google/Amazon/Meta?
Interval optimization, prefix sums, and sliding window problems appear frequently in interviews at companies like Google, Amazon, and Meta. Variants involving maximizing sums across ranges or windows are common system design and algorithm screening questions.
What data structure is used in Maximum Coins From K Consecutive Bags?
The problem primarily uses arrays for storing intervals, along with sorting and sliding window techniques. Prefix sums or partial overlap calculations are often used to compute contributions efficiently when intervals intersect the current window.
What is the time complexity of Maximum Coins From K Consecutive Bags?
The optimal solution runs in O(n log n) time because the intervals must be sorted before applying the sliding window logic. After sorting, each interval is processed at most a constant number of times. Space complexity is O(n) for storing intervals and prefix-style accumulations.

Ready to solve this problem?

Practice Maximum Coins From K Consecutive Bags with our built-in code editor and test cases.

Practice on FleetCode