Maximum Coins From K Consecutive Bags | Sliding Window | C++
Code


# Code
```cpp []
class Solution {
public:
    long long maximumCoins(vector<vector<int>>& coins, int k) {
        sort(coins.begin(), coins.end());
        vector<vector<int>> a;
        int start = coins[0][0];
        if(start > 1){
            a.push_back({1, start - 1, 0});
        }
        int last = start - 1;
        for(int i = 0; i<coins.size(); i++){
            int cur = coins[i][0];
            if(cur != last + 1){
                a.push_back({last + 1, cur - 1, 0});
            }
            a.push_back({cur, coins[i][1], coins[i][2]});
            last = coins[i][1];
        }

        start = a.back()[1];
        last = 1e9;
        if(start < last){
            a.push_back({start + 1, last, 0});
        }

        long long ans = 0;
        int ind = 0, total = 0, till = 0;
        for(int i = 0; i<a.size() && total < k; i++){
            int size = a[i][1] - a[i][0] + 1;
            if(size + total < k){
                ans += ((long long)size * (long long)a[i][2]);
                total += size;
            }else{
                int need = k - total;
                ans += ((long long)need * (long long)a[i][2]);
                total += need;
            }

            ind = i;
        }
        till = total;
        int from = 0, si = 0;
        long long cur = ans;
        for(int i = ind; i<a.size(); i++){
            int size = a[i][1] - till;
            
            if(size == 0) continue;
            else{
                update(a, si, i, from, till, ans, cur);
            } 
        }
        return ans;
    }

    void update(vector<vector<int>> &a, int &s, int &e, int &from, int &till, long long &ans, long long &cur){
        int size = a[e][1] - till;
        while(size > 0){
            int mini = min(size, a[s][1] - from);
            cur -= ((long long)a[s][2] * (long long)mini);
            cur += ((long long)a[e][2] * (long long)mini);
            size -= mini;
            from += mini;
            till += mini;
            ans = max(ans, cur);
           
            if(from >= a[s][1]) s++;
            if(s == e){
                from = a[e][1] - (till - from);
                till = a[e][1];
                size = 0;
            }
        }
    }

};
```
['C++']