Find permutation of numbers 1 to N having X local maxima (peaks) and Y local minima (valleys)

29 Dec, 2021
Given three integers N, A and B, the task is to find a permutation of pairwise distinct numbers from 1 to N that has exactly ‘A’ local minima’s and ‘B’ local maxima’s. 
A local minima is defined as the element which is less than both its neighbours.
A local maxima is defined as the element which is greater than both its neighbours.
The first and last element of the entire permutation can never be local minima or maxima.
If no such permutations exist print -1.
Example :
Input: N = 6 ,  A = 2 , B = 2Output:  1, 3, 2, 5, 4, 6Explanation : 2 local minima’s: 2 and 52 local maxima’s: 3 and 5
Input: N = 5 , A = 2 , B = 2Output: -1
Naive Approach (Brute Force): In this approach, generate all permutations of 1 to N numbers and check each one individually. Follow the below steps, to solve this problem:
Generate all the permutations of numbers from 1 to N and store them in an array.
Traverse through each permutation, if the following permutation has exactly A local minima’s and B local maxima’s, print the permutation.
If no such permutation exists, then print -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 generate next permutationvoid nextPermutation(vector<int>& nums){    int n = nums.size(), k, l;    for (k = n - 2; k >= 0; k--) {        if (nums[k] < nums[k + 1]) {            break;        }    }    if (k < 0) {        reverse(nums.begin(), nums.end());    }    else {        for (l = n - 1; l > k; l--) {            if (nums[l] > nums[k]) {                break;            }        }        swap(nums[k], nums[l]);        reverse(nums.begin() + k + 1, nums.end());    }}  // Factorial functionint factorial(int n){    return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;}  // Function to returns all the permutations of a given array// or vectorvector<vector<int> > permute(vector<int>& nums){    vector<vector<int> > permuted;    int n = nums.size();    int factn = factorial(n);    for (int i = 0; i < factn; i++) {        permuted.push_back(nums);        nextPermutation(nums);    }    return permuted;}  // Function to find the permutation of 1 to N numbers// having A minimas and B maximasvoid findPermutation(int n, int a, int b){      // Generate the array containing one permutation    vector<int> nums(n);    for (int i = 0; i < n; i++) {        nums[i] = i + 1;    }      // Generate all the permutations    vector<vector<int> > allpermutations = permute(nums);      int total = allpermutations.size();    int ansindex = -1;      for (int i = 0; i < total; i++) {        // Count local minima and local maximas for each        // permutation        int minc = 0, maxc = 0;        for (int j = 1; j < n - 1; j++) {            if (allpermutations[i][j]                    > allpermutations[i][j - 1]                && allpermutations[i][j]                       > allpermutations[i][j + 1]) {                maxc++;            }            if (allpermutations[i][j]                    < allpermutations[i][j - 1]                && allpermutations[i][j]                       < allpermutations[i][j + 1]) {                minc++;            }        }        if (minc == a && maxc == b) {              // Store the index of a perfect permutation            ansindex = i;            break;        }    }      // Print -1 if no such permutation exists    if (ansindex == -1) {        cout << -1;    }    else {        // Print the perfect permutation if exists        for (int i = 0; i < n; i++) {            cout << allpermutations[ansindex][i] << " ";        }    }}  int main(){    int N = 6, A = 2, B = 2;    findPermutation(N, A, B);    return 0;}
  
1 3 2 5 4 6 
 
Time Complexity: O(N!)Auxiliary Space: O(N!)
 
Efficient Approach (Greedy Method):
 
The above brute force method can be optimized using the Greedy Algorithm. Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. So, break the problem into different usable pieces according to the values of N, A, B. Follow the below steps to solve this problem:
 
As the first and the last element of an entire permutation cannot be maxima or minima so the total number of maxima’s and minima’s must be less than or equal to N-2. So if (A + B > N -2), print -1.
Also, there cannot be two consecutive minima’s or maxima’s. There must be a minima in between two consecutive maxima’s and there must be a maxima in between two consecutive minima’s. So the absolute difference between the total number of minima’s and maxima’s must be less than or equal to 1. So if the absolute difference between A and B exceeds 1 then print -1. We can easily visualize that from the image below.
After the two corner cases are done, create two variables, minValue to store the minimum value of the permutation, and maxValue to store the maxValue. Now divide the problem into three different cases that are (A > B), (A < B) and (A=B). Now solve each case individually:If (A > B): Initialize the minValue as 1 and fill the array with the minValue starting from index 2 for A times. After each insertion increase the minValue by 1 as the values should be distinct. While filling, make sure to leave one index empty after each insertion as it is not possible for two minima’s to reside consecutively. After creating A minima’s fill the rest of the array in increasing order so that no new minima is created.If (B > A): Initialize the maxValue as N and fill the array with the maxValue starting from index 2 for B times. After each insertion decrease the maxValue by 1 as the values should be distinct. While filling, make sure to leave one index empty after each insertion as it is not possible for two maxima’s to reside consecutively. After creating B maxima’s fill the rest of the array in decreasing order so that no new maxima is created.If (A = B): then initialize two values minValue as 1 and maxValue as N. Fill the first element of the array with minValue and increase the minValue by 1. Then fill the even indices with maxValue and decrease maxValue by 1 and fill the odd indices with minValue and increase the minValue by 1 for A times. Now, fill the rest of the positions in increasing order.
If (A > B): Initialize the minValue as 1 and fill the array with the minValue starting from index 2 for A times. After each insertion increase the minValue by 1 as the values should be distinct. While filling, make sure to leave one index empty after each insertion as it is not possible for two minima’s to reside consecutively. After creating A minima’s fill the rest of the array in increasing order so that no new minima is created.
If (B > A): Initialize the maxValue as N and fill the array with the maxValue starting from index 2 for B times. After each insertion decrease the maxValue by 1 as the values should be distinct. While filling, make sure to leave one index empty after each insertion as it is not possible for two maxima’s to reside consecutively. After creating B maxima’s fill the rest of the array in decreasing order so that no new maxima is created.
If (A = B): then initialize two values minValue as 1 and maxValue as N. Fill the first element of the array with minValue and increase the minValue by 1. Then fill the even indices with maxValue and decrease maxValue by 1 and fill the odd indices with minValue and increase the minValue by 1 for A times. Now, fill the rest of the positions in increasing order.
 
Below is the implementation of the above approach:
 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;  // Function to find the permutation of 1 to N numbers// having A minimas and B maximasvoid findPermutation(int N, int A, int B){        // Create the result array    vector<int> arr(N);    for (int i = 0; i < N; i++) {        arr[i] = -1;    }      // If the absolute difference between A and B is    // greater 1 or A+B is greater than N-2, then return -1    if (abs(A - B) > 1 || A + B > N - 2) {        cout << -1;    }    else {        if (A > B) {              // Initialize maxValue with N            int maxValue = N;              // Create a maxima's            for (int i = 1; i < N - 1 && A > 0; i += 2) {                arr[i] = maxValue;                maxValue--;                A--;            }              // Fill other elements in decreasing order            for (int i = 0; i < N; i++) {                if (arr[i] == -1) {                    arr[i] = maxValue;                    maxValue--;                }            }        }        else if (A < B) {            // Initialize minValue with 1            int minValue = 1;              // Create B minima's            for (int i = 1; i < N - 1 && B > 0; i += 2) {                arr[i] = minValue;                minValue++;                B--;            }              // Fill other elements in increasing order            for (int i = 0; i < N; i++) {                if (arr[i] == -1) {                    arr[i] = minValue;                    minValue++;                }            }        }        else if (A == B) {              // Initialize maxValue with n and minValue with            // 1            int minValue = 1, maxValue = N;            arr[0] = minValue;            minValue++;              // Initialize fill equal number of minima and            // maximas            for (int i = 1; i < N - 1 && A > 0; i += 2) {                arr[i] = maxValue;                arr[i + 1] = minValue;                A--;                maxValue--;                minValue++;            }              // Fill the rest in increasing order            for (int i = 0; i < N; i++) {                if (arr[i] == -1) {                    arr[i] = minValue;                    minValue++;                }            }        }          // Print the output        for (int i = 0; i < N; i++) {            cout << arr[i] << " ";        }    }    cout << endl;}  // Driver Codeint main(){    int N = 6, A = 2, B = 1;    findPermutation(N, A, B);      return 0;}
// Java program for the above approachclass GFG{  // Function to find the permutation of 1 to N numbers// having A minimas and B maximasstatic void findPermutation(int N, int A, int B){        // Create the result array    int []arr = new int[N];    for (int i = 0; i < N; i++) {        arr[i] = -1;    }      // If the absolute difference between A and B is    // greater 1 or A+B is greater than N-2, then return -1    if (Math.abs(A - B) > 1 || A + B > N - 2) {        System.out.print(-1);    }    else {        if (A > B) {              // Initialize maxValue with N            int maxValue = N;              // Create a maxima's            for (int i = 1; i < N - 1 && A > 0; i += 2) {                arr[i] = maxValue;                maxValue--;                A--;            }              // Fill other elements in decreasing order            for (int i = 0; i < N; i++) {                if (arr[i] == -1) {                    arr[i] = maxValue;                    maxValue--;                }            }        }        else if (A < B) {            // Initialize minValue with 1            int minValue = 1;              // Create B minima's            for (int i = 1; i < N - 1 && B > 0; i += 2) {                arr[i] = minValue;                minValue++;                B--;            }              // Fill other elements in increasing order            for (int i = 0; i < N; i++) {                if (arr[i] == -1) {                    arr[i] = minValue;                    minValue++;                }            }        }        else if (A == B) {              // Initialize maxValue with n and minValue with            // 1            int minValue = 1, maxValue = N;            arr[0] = minValue;            minValue++;              // Initialize fill equal number of minima and            // maximas            for (int i = 1; i < N - 1 && A > 0; i += 2) {                arr[i] = maxValue;                arr[i + 1] = minValue;                A--;                maxValue--;                minValue++;            }              // Fill the rest in increasing order            for (int i = 0; i < N; i++) {                if (arr[i] == -1) {                    arr[i] = minValue;                    minValue++;                }            }        }          // Print the output        for (int i = 0; i < N; i++) {            System.out.print(arr[i]+ " ");        }    }    System.out.println();}  // Driver Codepublic static void main(String[] args){    int N = 6, A = 2, B = 1;    findPermutation(N, A, B);  }}  // This code is contributed by 29AjayKumar
# Python 3 program for the above approach  # Function to find the permutation of 1 to N numbers# having A minimas and B maximasdef findPermutation(N, A, B):      # Create the result array    arr = [0]*(N)    for i in range(N):        arr[i] = -1      # If the absolute difference between A and B is    # greater 1 or A+B is greater than N-2, then return -1    if (abs(A - B) > 1 or A + B > N - 2):        print(-1)      else:        if (A > B):              # Initialize maxValue with N            maxValue = N              # Create a maxima's            i = 1            while i < N - 1 and A > 0:                arr[i] = maxValue                maxValue -= 1                A -= 1                i += 2              # Fill other elements in decreasing order            for i in range(N):                if (arr[i] == -1):                    arr[i] = maxValue                    maxValue -= 1        elif (A < B):            # Initialize minValue with 1            minValue = 1              # Create B minima's            i = 1            while i < N - 1 and B > 0:                arr[i] = minValue                minValue += 1                B -= 1                i += 2              # Fill other elements in increasing order            for i in range(N):                if (arr[i] == -1):                    arr[i] = minValue                    minValue += 1        elif (A == B):              # Initialize maxValue with n and minValue with            # 1            minValue = 1            maxValue = N            arr[0] = minValue            minValue += 1              # Initialize fill equal number of minima and            # maximas            i = 1            while i < N - 1 and A > 0:                arr[i] = maxValue                arr[i + 1] = minValue                A -= 1                maxValue -= 1                minValue += 1                i += 2              # Fill the rest in increasing order            for i in range(N):                if (arr[i] == -1):                    arr[i] = minValue                    minValue += 1          # Print the output        for i in range(N):            print(arr[i], end=" ")      print()  # Driver Codeif __name__ == "__main__":      N = 6    A = 2    B = 1    findPermutation(N, A, B)      # This code is contributed by ukasp.
// C# program for the above approachusing System;class GFG{    // Function to find the permutation of 1 to N numbers  // having A minimas and B maximas  static void findPermutation(int N, int A, int B)  {      // Create the result array    int []arr = new int[N];    for (int i = 0; i < N; i++) {      arr[i] = -1;    }      // If the absolute difference between A and B is    // greater 1 or A+B is greater than N-2, then return -1    if (Math.Abs(A - B) > 1 || A + B > N - 2) {      Console.Write(-1);    }    else {      if (A > B) {          // Initialize maxValue with N        int maxValue = N;          // Create a maxima's        for (int i = 1; i < N - 1 && A > 0; i += 2) {          arr[i] = maxValue;          maxValue--;          A--;        }          // Fill other elements in decreasing order        for (int i = 0; i < N; i++) {          if (arr[i] == -1) {            arr[i] = maxValue;            maxValue--;          }        }      }      else if (A < B) {        // Initialize minValue with 1        int minValue = 1;          // Create B minima's        for (int i = 1; i < N - 1 && B > 0; i += 2) {          arr[i] = minValue;          minValue++;          B--;        }          // Fill other elements in increasing order        for (int i = 0; i < N; i++) {          if (arr[i] == -1) {            arr[i] = minValue;            minValue++;          }        }      }      else if (A == B) {          // Initialize maxValue with n and minValue with        // 1        int minValue = 1, maxValue = N;        arr[0] = minValue;        minValue++;          // Initialize fill equal number of minima and        // maximas        for (int i = 1; i < N - 1 && A > 0; i += 2) {          arr[i] = maxValue;          arr[i + 1] = minValue;          A--;          maxValue--;          minValue++;        }          // Fill the rest in increasing order        for (int i = 0; i < N; i++) {          if (arr[i] == -1) {            arr[i] = minValue;            minValue++;          }        }      }        // Print the output      for (int i = 0; i < N; i++) {        Console.Write(arr[i]+ " ");      }    }    Console.Write("\n");  }    // Driver Code  public static void Main()  {    int N = 6, A = 2, B = 1;    findPermutation(N, A, B);    }}  // This code is contributed by Samim Hossain Mondal.
<script>   // JavaScript code for the above approach    // Function to find the permutation of 1 to N numbers   // having A minimas and B maximas   function findPermutation(N, A, B)   {          // Create the result array     let arr = new Array(N);     for (let i = 0; i < N; i++) {       arr[i] = -1;     }      // If the absolute difference between A and B is     // greater 1 or A+B is greater than N-2, then return -1     if (Math.abs(A - B) > 1 || A + B > N - 2) {       document.write(-1);     }     else {       if (A > B) {          // Initialize maxValue with N         let maxValue = N;          // Create a maxima's         for (let i = 1; i < N - 1 && A > 0; i += 2) {           arr[i] = maxValue;           maxValue--;           A--;         }          // Fill other elements in decreasing order         for (let i = 0; i < N; i++) {           if (arr[i] == -1) {             arr[i] = maxValue;             maxValue--;           }         }       }       else if (A < B)       {                  // Initialize minValue with 1         let minValue = 1;          // Create B minima's         for (let i = 1; i < N - 1 && B > 0; i += 2) {           arr[i] = minValue;           minValue++;           B--;         }          // Fill other elements in increasing order         for (let i = 0; i < N; i++) {           if (arr[i] == -1) {             arr[i] = minValue;             minValue++;           }         }       }       else if (A == B) {          // Initialize maxValue with n and minValue with         // 1         let minValue = 1, maxValue = N;         arr[0] = minValue;         minValue++;          // Initialize fill equal number of minima and         // maximas         for (let i = 1; i < N - 1 && A > 0; i += 2) {           arr[i] = maxValue;           arr[i + 1] = minValue;           A--;           maxValue--;           minValue++;         }          // Fill the rest in increasing order         for (let i = 0; i < N; i++) {           if (arr[i] == -1) {             arr[i] = minValue;             minValue++;           }         }       }        // Print the output       for (let i = 0; i < N; i++) {         document.write(arr[i] + " ");       }     }     document.write('<br>')   }    // Driver Code   let N = 6, A = 2, B = 1;   findPermutation(N, A, B);  // This code is contributed by Potta Lokesh </script>
  
4 6 3 5 2 1 
 
Time Complexity: O(N)Auxiliary Space: O(N)
 
lokeshpotta20
29AjayKumar
samim2000
ukasp
Algo-Geek 2021
Algo Geek
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X
Sort strings on the basis of their numeric part
Number of ways to divide a N elements equally into group of at least 2
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
Check if the given string is valid English word or not
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray