fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <utility>
  4. #include <algorithm>
  5. #include <vector>
  6.  
  7. std::pair<int, int> max_adj(std::vector<int> arr) {
  8. std::map<int, int> buckets;
  9.  
  10. for(int x = 0; x < arr.size(); x++) {
  11. // Loop to eat up adjacent values
  12. int in_a_row = 1;
  13. for(int curr = x++;
  14. x < arr.size() && arr[curr] == arr[x];
  15. x++, in_a_row++) { }
  16. x--; // The loop will increment x one past last dupe, so go back
  17.  
  18. // Only count every other adjacent value seen
  19. buckets[arr[x]] += (in_a_row + 1) / 2;
  20.  
  21. }
  22.  
  23. // Find the most seen
  24. std::map<int, int>::iterator mx = std::max_element
  25. (
  26. buckets.begin(), buckets.end(),
  27. [] (const std::pair<int, int> &p1, const std::pair<int, int> &p2) {
  28. return p1.second < p2.second;
  29. }
  30. );
  31.  
  32. if(mx != buckets.end()) {
  33. return *mx;
  34. }
  35. return std::pair<int, int>(-1, -1);
  36. }
  37.  
  38. int main() {
  39. std::vector<int> v1 {9,2,3,4,0,4,5,6,0,8};
  40. std::vector<int> v2 {4,4,4,4,4};
  41.  
  42. std::pair<int, int> p1 = max_adj(v1);
  43. std::pair<int, int> p2 = max_adj(v2);
  44.  
  45. std::cout << "Max adj val in v1: " << p1.first
  46. << " counted " << p1.second << " times" << std::endl;
  47. std::cout << "Max adj val in v2: " << p2.first
  48. << " counted " << p2.second << " times" << std::endl;
  49. return 0;
  50. }
Success #stdin #stdout 0s 4704KB
stdin
Standard input is empty
stdout
Max adj val in v1: 0 counted 2 times
Max adj val in v2: 4 counted 3 times