Maximum Coins From K Consecutive Bags Problem
Description
LeetCode Problem 3413.
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 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.
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 <= 10^51 <= k <= 10^9coins[i] == [l_i, r_i, c_i]1 <= l_i <= r_i <= 10^91 <= c_i <= 1000- The given segments are non-overlapping.
Solution
Approach: Prefix Sums + Binary Search
Positions go up to 109, so we cannot walk bag by bag. Instead, sort the segments and store prefix sums of the coins in whole segments. With that, upto(x), the number of coins in all bags at positions <= x, takes one binary search: find the last segment starting at or before x, then add the whole segments before it and the covered part of that segment.
The sum of a window [s, s + k - 1] is upto(s + k - 1) - upto(s - 1). An optimal window can always be slid until its left end sits on a segment's left end or its right end sits on a segment's right end, so we only try those 2 * n windows and keep the best.
Complexity: O(n log n) time and O(n) extra space.
from bisect import bisect_right
class Solution:
def maximumCoins(self, coins: List[List[int]], k: int) -> int:
coins = sorted(coins)
starts = [c[0] for c in coins]
pre = [0] # pre[i] = coins in the first i segments
for l, r, c in coins:
pre.append(pre[-1] + (r - l + 1) * c)
def upto(x): # coins in all bags at positions <= x
i = bisect_right(starts, x) - 1
if i < 0:
return 0
l, r, c = coins[i]
return pre[i] + (min(x, r) - l + 1) * c
ans = 0
for l, r, c in coins:
ans = max(ans, upto(l + k - 1) - upto(l - 1)) # window starts at a segment's left end
ans = max(ans, upto(r) - upto(r - k)) # window ends at a segment's right end
return ans