Cod sursa(job #2670302)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 9 noiembrie 2020 17:25:44
Problema Deque Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <queue>

int n, k, a;
int diff_max = INT32_MIN;
std::deque<std::pair<int, int>> dq_min, dq_max;

int main() {
  std::ifstream in("vila2.in");
  std::ofstream out("vila2.out");

  in >> n >> k;

  for (int i = 1; i <= n; ++i) {
    in >> a;

    // min
    if (!dq_min.empty() && dq_min.front().second < i - k)
      dq_min.pop_front();

    while (!dq_min.empty() && a < dq_min.back().first)
      dq_min.pop_back();

    dq_min.emplace_back(a, i);

    // max
    if (!dq_max.empty() && dq_max.front().second < i - k)
      dq_max.pop_front();

    while (!dq_max.empty() && a > dq_max.back().first)
      dq_max.pop_back();

    dq_max.emplace_back(a, i);

    // difference between min and max
    if (i > k && diff_max < dq_max.front().first - dq_min.front().first)
      diff_max = dq_max.front().first - dq_min.front().first;
  }

  out << diff_max << '\n';

  return 0;
}