Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
[ad_1]
Given two integers N and X, the duty is to search out an output array arr[] containing distinct integers of size N such that their common is Okay and the distinction between the minimal and the utmost is minimal attainable.
Enter: N = 4, X = 8
Output :- 6 7 9 10
Rationalization: Clearly the imply of 6, 7, 9, 10 is 8 and
The distinction between the max and the min is (10 – 6) = 4.Enter: N = 5, X = 15
Output: 13 14 15 16 17
Method: The issue may be solved primarily based on the next mathematical statement:
- For the distinction between max and min to be the minimal, the hole between the weather in sorted order should be minimal.
- For that each component when in sorted order ought to have minimal distinction from the common of array.
- So half of the weather must be within the left of Okay and half in proper and they need to have distinction = 1 between them
- If the worth of N is odd, then Okay may be current within the array.
- If the worth of N is even, then Okay can’t be a component, (as a result of then components in left of Okay and in proper of Okay won’t be the identical). The 2 center components will likely be Okay-1 and Okay+1 and all components within the left half and proper half have adjoining distinction = 1.
Comply with the steps under to unravel this downside primarily based on the above concept:
Beneath is the implementation of the above strategy :
|
Time Complexity: O(N)
Auxiliary House: O(1)
[ad_2]