Beautiful Arrangement II
The problem is about constructing an array of n different positive integers such that the array of absolute differences between adjacent elements contains exactly k distinct integers. We can achieve this by following these steps:
- Initialize the Array: Start by placing numbers 1 through n-k-1 in order in the array.
- Add k Distinct Differences: Now, we need to create k distinct differences between the adjacent elements. For this, we can alternate between adding and subtracting from n-k to create the required distinct differences.
- Build the Array: Keep adding elements to the array, alternating between adding and subtracting the next number until we have added k numbers.
Here’s the code:
|
|
Explanation:
- We first initialize the result array with numbers from 1 to n-k-1.
- Then, we add the next k+1 numbers to create k distinct differences between adjacent elements.
- We add and subtract numbers in an alternating manner to ensure that the differences are distinct.
For example, given n = 3, k = 2
, the output will be [1, 3, 2]
. The array has three different positive integers, and the absolute differences are [2, 1]
, which has exactly 2 distinct integers.