C++ program to find permutation with n peaks

Suppose we have two numbers n and k. We have to construct a permutation A using the numbers from 1 to n which has exactly k peaks. An index i is said to be peak of an array A, if A[i] > A[i-1] and A[i] > A[i+1]. If this is not possible, return -1.

So, if the input is like n = 5; k = 2, then the output will be [2, 4, 1, 5, 3], other answers are also possible.

Steps

To solve this, we will follow these steps −

if k > (n - 1) / 2, then:
   return -1
Define an array a of size: 101.
for initialize i := 1, when i 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;

void solve(int n, int k) {
   if (k > (n - 1) / 2) {
      cout 

Input

5, 2

Output

1, 3, 2, 5, 4,
Updated on: 2022-03-03T10:56:54+05:30

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements