C++ sort then iterate left to right and right to left
```cpp []
class Solution {
public:
    long long maximumCoins(vector<vector<int>>& coins, int k) {
        long long ans = 0;
        sort(coins.begin(), coins.end());
        vector<vector<long long>> p;
        long long sum = 0;
        for (auto& v : coins){
            long long nextSum = v[1] - v[0] + 1;
            nextSum *= v[2];
            p.push_back({v[0], v[1], sum += nextSum});
        }
        // from left
        k -= 1;
        for (int i = 0, r = 0; i < p.size(); ++i){
            while (r < p.size() && p[i][0] + k > p[r][1]){
                ++r;
            }
            long long topSum = r == p.size() ? p[r - 1][2] : p[r][2],
            lSum = i == 0 ? 0 : p[i - 1][2],
            tb = r < p.size() ? (p[r][1] - max(p[r][0] - 1, p[i][0] + k)) * coins[r][2] : 0;
            ans = max(ans, topSum - lSum - tb);
        }
        // from right
        for (int i = p.size() - 1, l = i; i >= 0; --i){
            while (l >= 0 && p[l][0] > p[i][1] - k){
                --l;
            }
            long long topSum = p[i][2];
            long long lSum = l == -1 ? 0 : p[l][2];
            long long tb = l == -1 ? 0 : max(coins[l][2] * (1 + p[l][1] - max(p[l][0], p[i][1] - k)), 0LL);
            ans = max(ans, topSum - lSum + tb);
        }
        return ans;
    }
};
```
['C++']