Advertisement
asdfg0998

cewcwec

Nov 15th, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. int longestSubarray(const vector<int>& salesData, int frequencyThreshold) {
  2.     unordered_map<int, int> freqMap;  // Frequency map to track counts of elements
  3.     int start = 0;
  4.     int maxLength = 0;
  5.  
  6.     for (int end = 0; end < salesData.size(); ++end) {
  7.         // Add current element to the frequency map
  8.         freqMap[salesData[end]]++;
  9.  
  10.         // If any frequency exceeds the threshold, move `start` to reduce the window
  11.         while (freqMap[salesData[end]] > frequencyThreshold) {
  12.             freqMap[salesData[start]]--;
  13.             if (freqMap[salesData[start]] == 0) {
  14.                 freqMap.erase(salesData[start]);  // Remove element if its frequency is 0
  15.             }
  16.             start++;
  17.         }
  18.  
  19.         // Update maxLength if the current window is longer
  20.         maxLength = max(maxLength, end - start + 1);
  21.     }
  22.  
  23.     return maxLength;
  24. }
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement