lovely_anna

```java []
class Solution {
    public long maximumCoins(int[][] a, int k) {
        var n = a.length;
        var sp = new TreeSet<int[]>((x, y) -> Long.compare(x[0], y[0]));
        var ep = new TreeSet<int[]>((x, y) -> Long.compare(x[0], y[0]));

        Arrays.sort(a, (x, y) -> x[0] - y[0]);
        for (var i = 0; i < n; i++) {
            sp.add(new int[] { a[i][0], i });
            ep.add(new int[] { a[i][1], i });
        }

        var pre = new long[n];
        pre[0] = (a[0][1] - a[0][0] + 1L) * a[0][2];
        for (var i = 1; i < n; i++)
            pre[i] = pre[i - 1] + (a[i][1] - a[i][0] + 1L) * a[i][2];

        var an = 0L;
        for (var i = 0; i < n; i++) {
            var l = a[i][1] - k + 1;
            var r = a[i][0] + k - 1;

            var ll = sp.ceiling(new int[] { l, 0 });
            var rr = ep.floor(new int[] { r, 0 });

            var lid = (ll != null ? ll[1] : i + 1);
            var rid = (rr != null ? rr[1] : i - 1);

            var lcom = (lid != i + 1
                        ? pre[i] - (lid != 0 ? pre[lid - 1] : 0)
                        : 0);
            var rcom = (rid != i - 1
                        ? pre[rid] - (i != 0 ? pre[i - 1] : 0)
                        : 0);

            var ladd = (lid != 0 && a[lid - 1][1] >= l
                        ? (a[lid - 1][1] - l + 1L) * a[lid - 1][2]
                        : 0);
            var radd = (rid != n - 1 && a[rid + 1][0] <= r
                        ? (r - a[rid + 1][0] + 1L) * a[rid + 1][2]
                        : 0);

            an = Math.max(an, Math.max(lcom + ladd, rcom + radd));
        }
        return an;
    }
}
```
['Java']