Algorithm/fastest-way2unified-data/main.cc

33 lines
690 B
C++
Raw Permalink Normal View History

2024-05-26 06:30:41 +00:00
#include <climits>
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
multiset<int> m;
int result = INT_MAX;
for (int i = 0; i < n - k + 1; i++) {
if (i == 0) {
for (int j = i; j <= i + k - 1; j++)
m.insert(arr[j]);
} else {
m.erase(arr[i - 1]);
m.insert(arr[i + k - 1]);
}
int count = 0;
auto middle_ptr = m.begin();
advance(middle_ptr, m.size() / 2);
for (const auto &element : m) {
count += abs(element - *middle_ptr);
}
result = min(result, count);
}
printf("%d\n", result);
}