Generate N sized Array with imply Okay and minimal distinction between min and max

[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:

  • Test the dimensions of output array (N) is even or odd
    • If even, then print all of the numbers from (M-N/2  to M+N/2) besides M itself.
    • In any other case, print all of the numbers from (M-N/2  to M+N/2) together with M.

Beneath is the implementation of the above strategy :

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

void findArray(int n, int x)

{

    int p, q, l;

  

    

    if (n % 2 != 0) {

        l = n / 2;

        p = x - l;

        q = l + x;

        for (int i = p; i <= q; i++)

            cout << i << " ";

    }

  

    

    else {

        l = n / 2;

        p = x - l;

        q = x + l;

        for (int i = p; i <= q; i++) {

            if (i != x)

                cout << i << " ";

        }

    }

}

  

int important()

{

    int N = 4, X = 8;

  

    

    findArray(N, X);

    return 0;

}

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

[ad_2]

Leave a Reply