Maximum Coins From K Consecutive Bags
MedPrompt
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 <= 1000- The given segments are non-overlapping.
Approaches
2 approaches with complexity analysis and trade-offs.
A straightforward but inefficient approach is to identify a set of potential optimal starting positions for the k consecutive bags and then calculate the sum for each. The key insight is that the maximum sum is likely achieved when the window of k bags aligns with the start or end of one of the coin intervals. This leads to a set of candidate start positions. For each candidate, we can perform a full calculation of the coins within that window by checking against all given coin intervals.
Algorithm
- Identify Candidate Start Positions: The total number of coins in a window of
kbags changes only when the window's start or end crosses the boundary of a coin interval. This suggests that the optimal window likely starts at a position related to these boundaries. A reasonable set of candidate start positions for the window[s, s+k-1]ares = l_iors = r_i - k + 1for every given interval[l_i, r_i, c_i]. - Iterate and Calculate: The algorithm iterates through each of these
O(N)candidate start positions. - Summation: For each candidate start position
s, it calculates the total coins in the window[s, s+k-1]. This is done by iterating through allNcoin intervals and summing up the contributions from each interval that overlaps with the window. - Overlap Calculation: The contribution of an interval
[l_j, r_j, c_j]isc_jmultiplied by the length of the intersection between[s, s+k-1]and[l_j, r_j]. - Track Maximum: The algorithm keeps track of the maximum sum found across all candidate windows and returns it as the result.
Walkthrough
This method is based on a brute-force check over a reduced search space. Instead of checking every possible start position on the number line (which is infinite), we only check positions that are 'critical'.
-
Generate Candidate Start Positions: We create a list of candidate start positions. For each interval
[l_i, r_i, c_i], the critical start points for a window of sizekarel_i(aligning the window's start with the interval's start) andr_i - k + 1(aligning the window's end with the interval's end). We collect all such unique, positive positions. -
Calculate Sum for Each Candidate: For each candidate start position
s, we calculate the total coins in the window[s, s + k - 1]. This is done by iterating through allNoriginal coin intervals[l_j, r_j, c_j]. For each interval, we find the length of its overlap with our window[s, s + k - 1]. The overlap length ismax(0, min(s + k - 1, r_j) - max(s, l_j) + 1). We multiply this length byc_jand add it to the total for the current window. -
Find Maximum: We maintain a variable
max_coinsand update it with the highest total found among all candidate windows.
import java.util.HashSet;import java.util.Set; class Solution { public long maximumCoins(int[][] coins, int k) { Set<Long> candidates = new HashSet<>(); for (int[] coin : coins) { long l = coin[0]; long r = coin[1]; candidates.add(l); if (r - k + 1 > 0) { candidates.add(r - k + 1); } } long maxTotalCoins = 0; for (long startPos : candidates) { long endPos = startPos + k - 1; long currentTotalCoins = 0; for (int[] coin : coins) { long l = coin[0]; long r = coin[1]; long c = coin[2]; long overlapStart = Math.max(startPos, l); long overlapEnd = Math.min(endPos, r); if (overlapStart <= overlapEnd) { long overlapLength = overlapEnd - overlapStart + 1; currentTotalCoins += overlapLength * c; } } maxTotalCoins = Math.max(maxTotalCoins, currentTotalCoins); } return maxTotalCoins; }}Complexity
Time
O(N^2), where N is the number of coin intervals. There are up to 2N candidate start positions. For each candidate, we iterate through all N intervals to calculate the sum, leading to a quadratic time complexity.
Space
O(N), where N is the number of coin intervals. This space is used to store the set of candidate start positions.
Trade-offs
Pros
Relatively simple to understand and implement.
Correctly identifies a smaller, finite set of candidate solutions to check.
Cons
The time complexity of
O(N^2)is too slow and will not pass the time limits for the given constraints (Nup to 10^5).
Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.