Code Submission Evaluation System Login

CSES - HIIT Open 2018

HIIT Open 2018

Contest start:2018-05-26 11:00:00
Contest end:2018-05-26 16:00:00

Task list | Submit code | Submissions | Messages | Scoreboard | Statistics


History
2018-05-26 11:49:38
2018-05-26 11:31:56
2018-05-26 11:30:04
Task:Buy Low, Sell High
Sender:HIIT AND RUN
Submission time:2018-05-26 11:49:38
Status:READY
Result:ACCEPTED

Show test data

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

vector<ll> v;

int main() {
    int n;
    cin >> n;
    
    v.resize(n);
    for (int i = 0; i < n; i++) {
        ll x;
        cin >> x;
        v[i] = x;
    }
    
    ll minStart = v[0];
    ll maxProfitAnywhereBetween = 0;
    vector<ll> l(n);
    
    for (int i = 0; i < n; i++) {
        minStart = min(minStart, v[i]);
        ll profitIfSellHere = v[i] - minStart;
        maxProfitAnywhereBetween = max(maxProfitAnywhereBetween, profitIfSellHere);
        l[i] = maxProfitAnywhereBetween;
    }
    
    ll maxEnd = v[n-1];
    maxProfitAnywhereBetween = 0;
    vector<ll> r(n);
    
    for (int i=n-1; i >= 0; i--) {
        maxEnd = max(maxEnd, v[i]);
        ll profitIfBuyHere = maxEnd - v[i];
        maxProfitAnywhereBetween = max(maxProfitAnywhereBetween, profitIfBuyHere);
        r[i] = maxProfitAnywhereBetween;
    }
    ll ans = 0;
    for (int i =0; i < n; i++) {
        ans = max(ans, l[i] + r[i]);
    }
    
    cout << ans << endl;
    
    
    
}