Given an array arr[] consisting of N integers, the task is to find the permutation of array elements such that the sum of odd indices elements is greater than or equal to the sum of even indices elements.
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 1 4 2 3
Explanation:
Consider the permutation of the given array as {1, 4, 2, 3}.
Now, the sum of elements at odd indices = (4 + 3) = 7 and the sum of elements at even indices = (1 + 2) = 3.
As the sum at odd indices elements is greater than the sum of even indices element. Therefore, print the current permutation.Input: arr[] = {123, 45, 67, 89, 60, 33}
Output: 33 123 45 89 60 67
Naive Approach: The simplest approach to solve the given problem is to generate all possible permutations of the given array and print that permutation of the array whose sum of odd indices elements is greater than or equal to the sum of even indices elements.
Time Complexity: O(N*N!)
Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized by sorting the given array and using Two Pointer Approach. Follow the steps below to solve the problem:
- Sort the given array arr[] in increasing order.
- Initialize two variables, say i as 0 and j as (N – 1).
- Iterate over the range [0, N – 1] using the variable K and perform the following steps:
- If the value of K is even then print the value of arr[i] and increment the value of i by 1.
- Otherwise, print the value of arr[j] and decrement the value of j by 1.
Below is the implementation of the above approach :
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the permutation of// array elements such that the sum of// elements at odd indices is greater// than sum of elements at even indicesvoid rearrangeArray(int arr[], int n){ // Sort the given array sort(arr, arr + n); // Initialize the two pointers int j = n - 1; int i = 0; // Traverse the array arr[] for (int k = 0; k < n; k++) { // Check if k is even if (k % 2 == 0) { cout << arr[i] << " "; // Increment the value // of i i++; } else { cout << arr[j] << " "; // Decrement the value // of j j--; } }} // Driver Codeint main(){ int arr[] = { 123, 45, 67, 89, 60, 33 }; int N = sizeof(arr) / sizeof(arr[0]); rearrangeArray(arr, N); return 0;} |
33 123 45 89 60 67
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


