Sunday, August 14, 2022
HomeSoftware DevelopmentGenerate Array with parts in given vary and median as Ok

# Generate Array with parts in given vary and median as Ok

Given two integers N and Ok and a spread [L, R], the duty is to construct an array whose parts are distinctive and within the vary [L, R] and the median of the array is Ok.

Examples:

Enter: N = 6, Ok = -1, L = -5, R = 5
Output: -4 -3 -2 0 1 2
Rationalization: Median = (-2 + 0)/2 = -1 which is the same as Ok.

Enter: N = 5, Ok = 4, L = 3, R = 8
Output: -1

Method: The issue will be solved utilizing the next mathematical thought:

• If the array is of strange size the median is the (N/2 + 1)th component after sorting.
• In any other case, the median would be the common of (N/2) anf (N/2 + 1)th parts.

So the optimum means is to make an array such that the minimal worth and the utmost worth are as near the median as potential.

This may be executed by merely conserving the distinction between the weather as 1.
Due to this fact the minimal component of the array wll be (Ok – N/2) and the utmost component might be (Ok + N/2).

Be aware: In case of N being even Ok is the common of two center parts. So these two parts have a distinction of two between them and Ok won’t be current within the array.

Comply with the steps talked about beneath to implement the commentary:

• Discover the potential minimal and most values of the array.
• If both L is larger than the minimal or R is lower than the utmost then the array can’t be constructed.
• In any other case, repair the minimal and generate all the weather by sustaining a spot of 1 between adjoining parts.
• Within the case of N being even, the hole between the center two parts might be 2.
• Return the generated array as the reply.

Under is the implementation of the above strategy:

## C++

 ` `  `#embrace ` `utilizing` `namespace` `std;` ` `  `vector<``int``> constructArray(``int` `N, ``int` `Ok, ``int` `L, ``int` `R)` ` R < (Ok + (N / 2)))` `        ``ans.push_back(-1);` `    ``else` `if` `(N & 1)` `        ``for` `(``int` `i = Ok - (N / 2);` `             ``i <= Ok + (N / 2); i++)` `            ``ans.push_back(i);` `    ``else` `        ``for` `(``int` `i = Ok - (N / 2);` `             ``i <= Ok + (N / 2); i++)` `            ``if` `(i != Ok)` `                ``ans.push_back(i);` `    ``return` `ans;` ` `  `int` `primary()` `{` `    ``int` `N = 6, Ok = -1;` `    ``int` `L = -5, R = 5;` ` `  `    ` `    ``vector<``int``> ans` `        ``= constructArray(N, Ok, L, R);` `    ``for` `(``int` `x : ans)` `        ``cout << x << ``" "``;` `    ``return` `0;` `}`

Time Complexity: O(N)
Auxiliary House: O(N)

RELATED ARTICLES