fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. int maxIncreasingPairs(vector<int>& ratings) {
  7. int n = ratings.size();
  8. sort(ratings.begin(), ratings.end());
  9.  
  10. vector<int> result(n);
  11. int mid = (n + 1) / 2;
  12. int j = 0;
  13.  
  14. // Place the smaller half elements at even indices
  15. for (int i = 0; i < n; i += 2) {
  16. result[i] = ratings[j++];
  17. }
  18.  
  19. // Place the larger half elements at odd indices
  20. for (int i = 1; i < n; i += 2) {
  21. result[i] = ratings[j++];
  22. }
  23.  
  24. // Count indices i where result[i] < result[i+1]
  25. int count = 0;
  26. for (int i = 0; i < n - 1; ++i) {
  27. if (result[i] < result[i + 1]) {
  28. count++;
  29. }
  30. }
  31.  
  32. // Optional: print the rearranged array
  33. cout << "Rearranged: ";
  34. for (int x : result) cout << x << " ";
  35. cout << endl;
  36.  
  37. return count;
  38. }
  39.  
  40. int main() {
  41. // Example 1
  42. vector<int> ratings1 = {2, 3, 1, 5, 4};
  43. cout << "Output: " << maxIncreasingPairs(ratings1) << endl;
  44.  
  45. // Example 2
  46. vector<int> ratings2 = {2, 1, 1, 2};
  47. cout << "Output: " << maxIncreasingPairs(ratings2) << endl;
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0.01s 5284KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
Output: Rearranged: 1 4 2 5 3 
2
Output: Rearranged: 1 2 1 2 
2