- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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,
- Related Articles
- C++ Program to find permutation from merged permutations
- Program to find indices or local peaks in Python
- Find n-th lexicographically permutation of a strings in C++
- Find the good permutation of first N natural numbers C++
- Java program to find the permutation when the values n and r are given
- Find Permutation in C++
- Program to find decode XORed permutation in Python
- C++ Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements From 1 to N
- Find the Number of permutation with K inversions using C++
- Program to find number of magic sets from a permutation of first n natural numbers in Python
- C++ Program for BogoSort or Permutation Sort?
- Find permutation of first N natural numbers that satisfies the given condition in C++
- Find n-th lexicographically permutation of a strings in Python
- C/C++ Program to Find the sum of Series with the n-th term as n^2 – (n-1)^2
- Program to find maximum sum obtained of any permutation in Python

Advertisements