- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
Advertisements