33 lines
690 B
C++
33 lines
690 B
C++
#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);
|
|
}
|