0w1

CFR 580 B. Kefa and Company ( Deque )

Problem - B - Codeforces
If the friends are sorted such that each of their money is in ascending order, any valid combinations, having maximised the largest value, will be a contiguous segment. Hence we will apply crawling technique to find the maximal value of such contiguous segments.

void solve(){
    int N, D; cin >> N >> D;
    vp m_s( N );
    for( int i = 0; i < N; ++i )
        cin >> m_s[ i ].first >> m_s[ i ].second;
    sort( m_s.begin(), m_s.end() );
    ll ans = -1;
    ll val = 0;
    deque< pii > dq;
    for( int i = 0; i < N; ++i ){
        val += m_s[ i ].second;
        dq.push_back( m_s[ i ] );
        while( dq.back().first - dq.front().first >= D )
            val -= dq.front().second,
            dq.pop_front();
        upmax( ans, val );
    }
    cout << ans << endl;
}