Input: coins =[[8,10,1],[1,3,2],[5,6,4]], k =4Output: 10Explanation:
Selecting bags at positions `[3, 4, 5, 6]` gives the maximum number of coins:`2 + 0 + 4 + 4 = 10`.
Since the segments are non-overlapping, we can flatten the segments into a list of (position, coins) and then use a prefix sum array to efficiently compute the sum of coins in any interval. We then slide a window of size k over all possible positions to find the maximum sum.
classSolution {
public:int maxCoins(vector<vector<int>>& coins, int k) {
map<int, int> pos;
for (auto& seg : coins) {
for (int i = seg[0]; i <= seg[1]; ++i) pos[i] += seg[2];
}
vector<pair<int, int>> arr(pos.begin(), pos.end());
int n = arr.size(), ans =0, sum =0, l =0;
for (int r =0; r < n; ++r) {
sum += arr[r].second;
while (arr[r].first - arr[l].first +1> k) {
sum -= arr[l].second;
++l;
}
if (arr[r].first - arr[l].first +1== k)
ans = max(ans, sum);
}
return ans;
}
};
classSolution {
publicintmaxCoins(int[][] coins, int k) {
TreeMap<Integer, Integer> pos =new TreeMap<>();
for (int[] seg : coins) {
for (int i = seg[0]; i <= seg[1]; ++i) pos.put(i, pos.getOrDefault(i, 0) + seg[2]);
}
List<Integer> keys =new ArrayList<>(pos.keySet());
int n = keys.size(), ans = 0, sum = 0, l = 0;
for (int r = 0; r < n; ++r) {
sum += pos.get(keys.get(r));
while (keys.get(r) - keys.get(l) + 1 > k) {
sum -= pos.get(keys.get(l));
++l;
}
if (keys.get(r) - keys.get(l) + 1 == k)
ans = Math.max(ans, sum);
}
return ans;
}
}
classSolution {
funmaxCoins(coins: Array<IntArray>, k: Int): Int {
val pos = mutableMapOf<Int, Int>()
for (seg in coins) {
for (i in seg[0]..seg[1]) pos[i] = pos.getOrDefault(i, 0) + seg[2]
}
val keys = pos.keys.sorted()
val arr = keys.map { pos[it]!! }
var ans = 0var sum = 0var l = 0for (r in keys.indices) {
sum += arr[r]
while (keys[r] - keys[l] + 1 > k) {
sum -= arr[l]
l++ }
if (keys[r] - keys[l] + 1== k)
ans = maxOf(ans, sum)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defmaxCoins(self, coins: list[list[int]], k: int) -> int:
from collections import defaultdict
pos = defaultdict(int)
for l, r, c in coins:
for i in range(l, r+1):
pos[i] += c
keys = sorted(pos)
arr = [pos[x] for x in keys]
ans = s = l =0for r in range(len(keys)):
s += arr[r]
while keys[r] - keys[l] +1> k:
s -= arr[l]
l +=1if keys[r] - keys[l] +1== k:
ans = max(ans, s)
return ans
impl Solution {
pubfnmax_coins(coins: Vec<Vec<i32>>, k: i32) -> i32 {
use std::collections::BTreeMap;
letmut pos = BTreeMap::new();
for seg in coins {
for i in seg[0]..=seg[1] {
*pos.entry(i).or_insert(0) += seg[2];
}
}
let keys: Vec<_>= pos.keys().cloned().collect();
let arr: Vec<_>= keys.iter().map(|&x| pos[&x]).collect();
letmut ans =0;
letmut sum =0;
letmut l =0;
for r in0..keys.len() {
sum += arr[r];
while keys[r] - keys[l] +1> k {
sum -= arr[l];
l +=1;
}
if keys[r] - keys[l] +1== k {
ans = ans.max(sum);
}
}
ans
}
}