VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-array-which-when-sorted-forms-an-ap-and-has-minimum-maximum/

⇱ Find the Array which when sorted forms an AP and has minimum maximum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Array which when sorted forms an AP and has minimum maximum

Last Updated : 29 Nov, 2021

Given three positive integers N, X, and Y(X<Y). The task is to find an array of length N containing both X and Y, and when sorted in increasing order, the array must form an arithmetic progression

Examples:

Input: N = 5, X = 20, Y = 50
Output: 20 30 40 50 10 
Explanation: The array when sorted in increasing order forms an arithmetic progression with common difference 10.

Input: N = 17, X = 23445, Y = 1000000
Output: 23445 218756 414067 609378 804689 1000000 1195311 1390622 1585933 1781244 1976555 2171866 2367177 2562488 2757799 2953110 3148421 
Explanation: The array when sorted in increasing order forms an arithmetic progression with common difference 195311.

Approach: In this problem, it can be observed that if the maximum element is to be minimized, then it can be assumed that Y should be the greatest element. If Y is the greatest, then each of the remaining elements will be less than or equal to Y. If Y is not the greatest element in the array, then elements greater than Y can be considered.

Follow the steps below to solve the given problem:

  • Check if some elements which have a common difference are present between X and Y. For this, check if (Y-X) is divisible by (N-1). If it is divisible, then decrease N and the common difference d is given by:

d = (Y-X)/(N-1)

  • If it is not divisible, then decrease (n-1) and repeat the above step in a loop till the denominator is non-zero.
  • If there don't exist any such elements between X and Y, then the common difference d is given by:

d = (Y-X)

  • Let the resultant array be stored in vector ans. Push the elements found between X and Y in the vector ans to use a for loop.
  • If N is not equal to zero, insert the elements in ans starting from (X-d) with common difference d.
  • If N is equal to zero, output ans. Otherwise, insert the elements in ans starting from (Y+d) till the required array is obtained.

Below is the implementation of the above approach:


Output
20 30 40 50 10 

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

Comment