公式

E - Make Them Narrow 解説 by en_translator


Removing \(K\) elements of \(A\) is equivalent to retaining \((N-K)\) elements to form \(B\).
Let us fix an element that becomes the minimum value of \(B\). Let \(A_x\) be this value.
In order to minimize (maximum value of \(B\)) - (minimum value of \(B\)), it is optimal to retain the \((N-K)\) smallest elements among the elements of \(A\) greater than or equal to \(A_x\).
In other words, it is optimal to choose \((N-K)\) consecutive elements in \(A\) sorted in ascending order.

Then, the following solution is effective:

  • First, sort \(A\) so that \(A_1 \le A_2 \le \dots \le A_N\).
  • Then, the answer is the minimum value of \(A_{l+(N-K)-1}-A_l\) for \(1 \le l \le K+1\).
    • This is equivalent to fixing \(A_l\) as (minimum value of \(B\)), and retaining consecutive \((N-K)\) elements.

This can be implement with sorting and a for loop. The total time complexity is \(O(N \log N)\).

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int n,k;
  cin >> n >> k;
  vector<int> a(n);
  for(auto &nx : a){cin >> nx;}

  sort(a.begin(),a.end());
  int res=2e9;
  for(int i=0;i<=k;i++){
    res=min(res,a[i+(n-k)-1]-a[i]);
  }
  cout << res << "\n";
  return 0;
}

投稿日時:
最終更新: