fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. #define print(a) for(auto x : a) cout << x << " "; cout << endl
  6.  
  7.  
  8. const int M = 1000000007;
  9. const int N = 3e5+9;
  10. const int INF = 2e9+1;
  11. const int LINF = 2000000000000000001;
  12.  
  13. inline int power(int a, int b, int mod=M) {
  14. int x = 1;
  15. a %= mod;
  16. while (b) {
  17. if (b & 1) x = (x * a) % mod;
  18. a = (a * a) % mod;
  19. b >>= 1;
  20. }
  21. return x;
  22. }
  23.  
  24.  
  25. //_ ***************************** START Below *******************************
  26.  
  27.  
  28.  
  29.  
  30. vector<int> a;
  31. int count(int n, int x){
  32. int ct = 0;
  33. int s = 0, e = 0;
  34.  
  35. while(e<n && s<n-1){
  36. if(s==e) e++;
  37. if(a[e]-a[s] <= x){
  38. e++;
  39. ct += e-s;
  40. }
  41. else{
  42. s++;
  43. }
  44.  
  45. }
  46.  
  47. return ct;
  48. }
  49.  
  50. int consistency(int n, int k){
  51.  
  52. sort(begin(a), end(a));
  53.  
  54. int s = 0, e = a[n-1]-a[0];
  55.  
  56. while(s<e){
  57. int mid = s + (e-s)/2;
  58. if(count(n, mid) >= k){
  59. e = mid;
  60. }
  61. else s = mid+1;
  62. }
  63.  
  64. return e;
  65.  
  66. }
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82. int practice(int n, int k){
  83.  
  84.  
  85. return 0;
  86. }
  87.  
  88.  
  89.  
  90.  
  91.  
  92. void solve() {
  93.  
  94. int n, k;
  95. cin>> n >> k;
  96.  
  97. a.resize(n);
  98. for(int i=0; i<n; i++) cin >> a[i];
  99.  
  100. cout << consistency(n, k) << endl;
  101.  
  102.  
  103. }
  104.  
  105.  
  106.  
  107.  
  108.  
  109. int32_t main() {
  110. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  111.  
  112. int t = 1;
  113. // cin >> t;
  114. while (t--) {
  115. solve();
  116. }
  117.  
  118. return 0;
  119. }
Success #stdin #stdout 0s 5324KB
stdin
7 20
1 2 2 3 4 4 5
stdout
2