- Related Questions & Answers
- Average numbers in array in C Programming
- C Program to Multiply two Floating Point Numbers?
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C programming
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of first n natural numbers in C Program
- Number of elements a particular tag contains in JavaScript?
- Sum of squares of first n natural numbers in C Program?
- Sum of squares of the first n even numbers in C Program
- Dynamically add elements in ListView in android?
- What is the difference between Enumeration interface and enum in Java?
- Can we add null elements to a Set in Java?
- Find all the numbers in a string using regular expression in Python
- Count frequencies of all elements in array in Python using collections module
- Lambda expression in Python to rearrange positive and negative numbers
- Count distinct elements in an array in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We have the first N natural numbers. Our task is to get one permutation of them where the absolute difference between every two consecutive elements is > 1. If no such permutation is present, return -1.

The approach is simple. We will use the greedy approach. We will arrange all odd numbers in increasing or decreasing order, then arrange all even numbers in decreasing or increasing order

Begin if N is 1, then return 1 if N is 2 or 3, then return -1 as no such permutation is not present even_max and odd_max is set as max even and odd number less or equal to n arrange all odd numbers in descending order arrange all even numbers in descending order End

#include <iostream> using namespace std; void arrangeN(int N) { if (N == 1) { //if N is 1, only that will be placed cout << "1"; return; } if (N == 2 || N == 3) { //for N = 2 and 3, no such permutation is available cout << "-1"; return; } int even_max = -1, odd_max = -1; //find max even and odd which are less than or equal to N if (N % 2 == 0) { even_max = N; odd_max = N - 1; } else { odd_max = N; even_max = N - 1; } while (odd_max >= 1) { //print all odd numbers in decreasing order cout << odd_max << " "; odd_max -= 2; } while (even_max >= 2) { //print all even numbers in decreasing order cout << even_max << " "; even_max -= 2; } } int main() { int N = 8; arrangeN(N); }

7 5 3 1 8 6 4 2

Advertisements