fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n, k;
  6. cin >> n >> k;
  7. vector<int> arr(n);
  8. for (int i = 0; i < n; i++) {
  9. cin >> arr[i];
  10. }
  11.  
  12. int i = 0, j = 0, ans = 0;
  13. while (j < n) {
  14. // Since the array is sorted, calculate the difference directly
  15. if (arr[j] - arr[i] <= k) {
  16. ans = max(ans, j - i + 1); // Update the maximum length
  17. j++; // Expand the window
  18. } else {
  19. i++; // Shrink the window
  20. }
  21. }
  22.  
  23. cout << ans;
  24. return 0;
  25. }
  26.  
Success #stdin #stdout 0.01s 5284KB
stdin
7 4
1 2 3 6 7 8 10
stdout
4