Given two integers N and K where K < N, the task is to generate a permutation of integers from 1 to N such that the absolute difference of all the consecutive integers give exactly K distinct integers.
Input: N = 3, K = 2
Output: 1 3 2
|1 – 3| = 2 and |3 – 2| = 1 which gives 2 distinct integers (2 and 1)
Input: N = 5, K = 4
Output: 1 5 2 4 3
|1 – 5| = 4, |5 – 2| = 3, |2 – 4| = 2 and |4 – 3| = 1 gives 4 distinct integers i.e. 4, 3, 2 and 1
Approach: The problem can be easily solved by simple observation. At the odd indices place increasing sequence 1, 2, 3, … and at the even indices place the decreasing sequence N, N-1, N-2, … and so on.
For N = 10, a permutation with distinct integers for consecutive absolute difference can be 1 10 2 9 3 8 4 7 5 6. The consecutive absolute difference gives integers 9, 8, 7 and so on.
So, first print K integers of such a sequence then make the rest of the differences equal to 1. The code is quite self explanatory.
Below is the implementation of the above approach:
1 10 2 9 8 7 6 5 4 3
- Pair of prime numbers with a given sum and minimum absolute difference
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Number of distinct integers obtained by lcm(X, N)/X
- Minimum absolute difference between N and a power of 2
- Largest subset where absolute difference of any two element is a power of 2
- Check if array can be divided into two sub-arrays such that their absolute difference is K
- Pair with minimum absolute difference after solving each query
- Count maximum elements of an array whose absolute difference does not exceed K
- Check if elements of an array can be arranged in a Circle with consecutive difference as 1
- Find the good permutation of first N natural numbers
- Find two distinct prime numbers with given product
- Number of distinct prime factors of first n natural numbers
- Queries to return the absolute difference between L-th smallest number and the R-th smallest number
- Difference between the summation of numbers whose frequency of all digits are same and different
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.