fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long int ll;
  4.  
  5. // Function to count subarrays with at most `k` distinct elements
  6. ll count(ll arr[], int n, int k) {
  7. ll i = 0, j = 0, count = 0;
  8. unordered_map<ll, ll> freq; // To store the frequency of elements in the current window
  9.  
  10. while (j < n) {
  11. // Expand the window by including the current element
  12. freq[arr[j]]++;
  13.  
  14. // If the number of distinct elements exceeds `k`, shrink the window
  15. while (freq.size() > k) {
  16. freq[arr[i]]--;
  17. if (freq[arr[i]] == 0) {
  18. freq.erase(arr[i]);
  19. }
  20. i++; // Shrink the window from the left
  21. }
  22.  
  23. // Add the number of subarrays ending at `j`
  24. count += (j - i + 1);
  25.  
  26. // Move to the next element
  27. j++;
  28. }
  29.  
  30. return count;
  31. }
  32.  
  33. int main() {
  34. ll n;
  35. cin >> n;
  36. ll b[n];
  37.  
  38. for (ll i = 0; i < n; i++) cin >> b[i];
  39.  
  40. ll tot = n * (n + 1) / 2; // Total number of subarrays
  41. ll v = (tot + 1) / 2; // Half of total subarrays, rounded up
  42.  
  43. // Binary search for the smallest `r` such that count(b, n, r) >= v
  44. ll left = 1, right = n, r = n;
  45. while (left <= right) {
  46. ll mid = (left + right) / 2;
  47. if (count(b, n, mid) >= v) {
  48. r = mid; // Potential answer
  49. right = mid - 1; // Try to find a smaller valid `r`
  50. } else {
  51. left = mid + 1; // Increase `r`
  52. }
  53. }
  54.  
  55. cout << r << endl;
  56. return 0;
  57. }
Success #stdin #stdout 0.01s 5288KB
stdin
5  
5 5 2 2 1 
stdout
2