Maximizing the elements with a[i+1] > a[i] in C++


Problem statement

Given an array of N integers, rearrange the array elements such that the next array element is greater than the previous element arr[i+1] > arr[i]

Example

If input array is {300, 400, 400, 300} then rearranged array will be −

{300, 400, 300, 400}. In this solution we get 2 indices with condition arr[i+1] > arr[i]. Hence answer is 2.

Algorithm

  • If all elements are distinct, then answer is simply n-1 where n is the number of elements in the array
  • If there are repeating elements, then answer is n – maxFrequency

Example

Let us now see an example −

 Live Demo

#include <bits/stdc++.h>
#define MAX 1000
using namespace std;
int getMaxIndices(int *arr, int n) {
   int count[MAX] = {0};
   for (int i = 0; i < n; ++i) {
      count[arr[i]]++;
   }
   int maxFrequency = 0;
   for (int i = 0; i < n; ++i) {
      if (count[arr[i]] > maxFrequency) {
         maxFrequency = count[arr[i]];
      }
   }
   return n - maxFrequency;
}
int main() {
   int arr[] = {300, 400, 300, 400}; int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Answer = " << getMaxIndices(arr, n) << endl;
   return 0;
}

Output

Answer = 2

Updated on: 31-Dec-2019

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements