# 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 <= n, update (increase i by 1), do:
a[i] := i
for initialize i := 2, when i <= 2 * k, update i := i + 2, do:
swap a[i] and a[i + 1]
for initialize i := 1, when i <= n, update (increase i by 1), do:
print a[i]

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(int n, int k) {
if (k > (n - 1) / 2) {
cout << "-1";
return;
}
int a[101];
for (int i = 1; i <= n; i++)
a[i] = i;
for (int i = 2; i <= 2 * k; i += 2) {
swap(a[i], a[i + 1]);
}
for (int i = 1; i <= n; i++)
cout << a[i] << ", ";
}
int main() {
int n = 5;
int k = 2;
solve(n, k);
}

## Input

5, 2

## Output

1, 3, 2, 5, 4,