fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int maxEqualSubsequenceLength(vector<int>& arr, int k) {
  9. map<int, int> freqMap;
  10.  
  11. // Calculate the ranges and fill the frequency map
  12. for (int num : arr) {
  13. freqMap[num - k]++; // Start of the range
  14. freqMap[num + k + 1]--; // End of the range + 1
  15. }
  16.  
  17. int maxLength = 0;
  18. int currentLength = 0;
  19.  
  20. // Compute prefix sums
  21. for (auto& entry : freqMap) {
  22. currentLength += entry.second; // Update current length
  23. maxLength = max(maxLength, currentLength); // Update max length
  24. }
  25.  
  26. return maxLength;
  27. }
  28.  
  29. int main() {
  30. vector<int> arr = {1, 2, 3, 4, 5};
  31. int k = 1;
  32. cout << "Maximum length of equal subsequence: " << maxEqualSubsequenceLength(arr, k) << endl;
  33. return 0;
  34. }
  35.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Maximum length of equal subsequence: 3