SELL2 - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: raysh07
Tester: sushil2006
Editorialist: raysh07

DIFFICULTY:

Simple

PREREQUISITES:

Greedy/DP

PROBLEM:

You get one new watch every day. You can sell upto 2 watches every day for A_i coins. What is your maximum profit?

EXPLANATION:

There are 2 fundamental approaches to it, either through regret greedy or through dynamic programming.

Regret Greedy:

For each prefix of the array A, maintain the optimal choices in a multiset. Then, incrementally from i = 1 to N, sell 1 watch on day i and insert A_i into the multiset. Further, if A_i is better than the minimum value in the multiset, remove it and insert A_i again into the multiset (this is representing overwriting a previous choice with selling on day i instead).

This has a time complexity of O(N \cdot log (N)).

Dynamic Programming:

We can maintain a dp state of dp_{(i, j)} = maximum profit with selling j items upto day i. Note that a state is valid if and only if j \le i because we cannot sell items we do not have.

Then, we loop over the number of items sold on day i + 1 (can be 0, 1 or 2) and transition accordingly.

The final answer can be found in dp_{(N, N)}. There are O(N^2) states each with O(1) transitions, hence the time complexity is O(N^2)

TIME COMPLEXITY:

\mathcal{O}(N log(N)) per testcase.

CODE:

Editorialist's Code (C++)
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18

mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());

void Solve() 
{
    int n; cin >> n;
    
    vector <int> a(n);
    for (auto &x : a) cin >> x;
    
    multiset <int> ms;
    for (auto x : a){
        ms.insert(x);
        int y = *ms.begin();
        if (y < x){
            ms.erase(ms.find(y));
            ms.insert(x);
        }
    }
    
    int ans = 0;
    for (auto x : ms){
        ans += x;
    }
    
    cout << ans << "\n";
}

int32_t main() 
{
    auto begin = std::chrono::high_resolution_clock::now();
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    // freopen("in",  "r", stdin);
    // freopen("out", "w", stdout);
    
    cin >> t;
    for(int i = 1; i <= t; i++) 
    {
        //cout << "Case #" << i << ": ";
        Solve();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n"; 
    return 0;
}