Generate N sized Array with mean K and minimum difference between min and max
Given two integers N and X, the task is to find an output array arr containing distinct integers of length N such that their average is K and the difference between the minimum and the maximum is minimum possible.
Input: N = 4, X = 8
Output :- 6 7 9 10
Explanation: Clearly the mean of 6, 7, 9, 10 is 8 and
The difference between the max and the min is (10 – 6) = 4.
Input: N = 5, X = 15
Output: 13 14 15 16 17
Approach: The problem can be solved based on the following mathematical observation:
- For the difference between max and min to be the minimum, the gap between the elements in sorted order must be minimum.
- For that every element when in sorted order should have minimum difference from the average of array.
- So half of the elements should be in the left of K and half in right and they should have difference = 1 between them
- If the value of N is odd, then K can be present in the array.
- If the value of N is even, then K cannot be a part, (because then elements in left of K and in right of K will not be the same). The two middle elements will be K-1 and K+1 and all elements in the left part and right part have adjacent difference = 1.
Follow the steps below to solve this problem based on the above idea:
- Check the size of output array (N) is even or odd
- If even, then print all the numbers from (M-N/2 to M+N/2) except M itself.
- Otherwise, print all the numbers from (M-N/2 to M+N/2) including M.
Below is the implementation of the above approach :
6 7 9 10
Time Complexity: O(N)
Auxiliary Space: O(1)