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 12:37:33
2018-05-26 12:32:32
Task:Buy Low, Sell High
Sender:Lucinda
Submission time:2018-05-26 12:37:33
Status:READY
Result:ACCEPTED

Show test data

Code

#include <iostream>
#include <string>
#include <stdio.h>
#include <math.h>
#include <vector>

using namespace std;

int main() {
    int n;
    cin >> n;
    int *a = new int[n];
    
    for (int i = 0; i < n; i++)
        cin >> a[i];

    int *b_pref = new int[n];
    int *b_suf = new int[n];
    b_pref[0] = 0; // first day buy and sell
    b_suf[n - 1] = 0; // last day buy and sell

    int lowest = a[0];
    
    for (int i = 1; i < n; i++) { // points at end of period
        int end = a[i];
        int best_so_far = b_pref[i - 1];
        
        if (end - lowest > best_so_far) b_pref[i] = end - lowest;
        else b_pref[i] = best_so_far;

        if (end < lowest) lowest = end;
    }
    
    /* cout << endl;
    for (int i = 0; i < n; i++)
        cout << b_pref[i] << " ";
    */
    int highest = a[n - 1];
    for (int i = n - 2; i >= 0; i--) { // points at the start of period
        int start = a[i];
        int best_so_far = b_suf[i + 1];
        
        if (highest - start > best_so_far) b_suf[i] = highest - start;
        else b_suf[i] = best_so_far;

        if (start > highest) highest = start;
    }

    /* cout << endl;
    for (int i = 0; i < n; i++)
        cout << b_suf[i] << " ";
    */
    int best = 0;
    for (int i = 0; i < n; i++) {
        if (b_pref[i] + b_suf[i] > best)
            best = b_pref[i] + b_suf[i];
    }
    cout << best << endl;
    
    delete[] a;
    delete[] b_pref;
    delete[] b_suf;
}