fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int n;
  7. cin>>n; // 5
  8.  
  9. int a[n];
  10. for(int i=0; i<n; i++)
  11. {
  12. cin>>a[i]; // 1 1 2 3 4
  13. }
  14.  
  15. int k;
  16. cin>>k; // 3
  17.  
  18. int i=0 , j=0; int sum = 0; int ans = -1;
  19.  
  20. unordered_map<int,int>mp;
  21.  
  22. while(j<n)
  23. {
  24. //calculation part
  25. sum = sum + a[j]; // Running sum find out kela
  26. mp[a[j]] = mp[a[j]] + 1; // increment the map to count the frequency of each element
  27.  
  28. if(j-i+1 < k)
  29. {
  30. j++;
  31. }
  32. else if(j-i+1 == k)
  33. {
  34. // mp.size means map madhe jevdhe elements sarvanchi frequency same aahe... tar mg ti equal to k honar
  35. if(mp.size() == k)
  36. {
  37. ans = max(ans , sum); // get the maximum sum
  38. }
  39.  
  40. // for a window mp.size() < k then it means duplicates are present in the window
  41. // and then whatever value is present in the sum can not be the potential ans
  42.  
  43. // slide the window
  44. sum = sum - a[i]; // Remove that ' i ' index Element from sum it will decrease the sum
  45. mp[a[i]] = mp[a[i]] - 1; // also remove from map it will Decrease the frequency from the map
  46.  
  47. // if frequency of that particular element becomes zero in map
  48. if(mp[a[i]] == 0)
  49. {
  50. mp.erase(a[i]); // Remove the element from map also
  51. }
  52.  
  53. // Increment both the pointers
  54. i++;
  55.  
  56. j++;
  57. }
  58. }
  59. cout<<ans<<" ";
  60. }
Success #stdin #stdout 0s 5324KB
stdin
5
1 1 2 3 4
3
stdout
9