Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Min difference between maximum and minimum element in all Y size subarrays
Next article icon

Generate N sized Array with mean K and minimum difference between min and max

Last Updated : 11 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to find the output array // of length N whose mean is equal to X void findArray(int n, int x) {     int p, q, l;      // If array size to be constructed is odd.     if (n % 2 != 0) {         l = n / 2;         p = x - l;         q = l + x;         for (int i = p; i <= q; i++)             cout << i << " ";     }      // If array size to be constructed is even     else {         l = n / 2;         p = x - l;         q = x + l;         for (int i = p; i <= q; i++) {             if (i != x)                 cout << i << " ";         }     } }  // Driver code int main() {     int N = 4, X = 8;      // Function call     findArray(N, X);     return 0; } 
Java
// Java code to implement the approach import java.io.*;  class GFG  {    // Function to find the output array   // of length N whose mean is equal to X   public static void findArray(int n, int x)   {     int p = 0, q = 0, l = 0;      // If array size to be constructed is odd.     if (n % 2 != 0) {       l = n / 2;       p = x - l;       q = l + x;       for (int i = p; i <= q; i++)         System.out.print(i + " ");     }      // If array size to be constructed is even     else {       l = n / 2;       p = x - l;       q = x + l;       for (int i = p; i <= q; i++) {         if (i != x)           System.out.print(i + " ");       }     }   }    // Driver Code   public static void main(String[] args)   {     int N = 4, X = 8;      // Function call     findArray(N, X);   } }  // This code is contributed by Rohit Pradhan 
Python3
# Python3 code to implement the approach  # Function to find the output array # of length N whose mean is equal to X def findArray(n,x):        # If array size to be constructed is odd.     a=n%2     if (a is not 0):         l = int(n / 2)         p = int(x - l)         q = int(l + x)         for i in range(p,q+1):             print(i,"",end='')                  # If array size to be constructed is even     else:         l = int(n / 2)         p = int(x - l)         q = int(x + l)         for i in range(p,q+1):             if (i is not x):                 print(i,"",end='') # Driver code N = 4 X = 8  # Function call findArray(N,X)  # This code is contributed by ashishsingh13122000. 
C#
// C# program to implement // the above approach using System; class GFG {    // Function to find the output array   // of length N whose mean is equal to X   public static void findArray(int n, int x)   {     int p = 0, q = 0, l = 0;      // If array size to be constructed is odd.     if (n % 2 != 0) {       l = n / 2;       p = x - l;       q = l + x;       for (int i = p; i <= q; i++)         Console.Write(i + " ");     }      // If array size to be constructed is even     else {       l = n / 2;       p = x - l;       q = x + l;       for (int i = p; i <= q; i++) {         if (i != x)           Console.Write(i + " ");       }     }   }  // Driver Code public static void Main() {     int N = 4, X = 8;      // Function call     findArray(N, X); } }  // This code is contributed by code_hunt. 
JavaScript
<script>         // Javascript code to implement the approach                  // Function to find the output array         // of length N whose mean is equal to X         function findArray(n, x){             let p;             let q;             let l;                      // If array size to be constructed is odd.             if (n % 2 !== 0) {                 l = n / 2;                 p = x - l;                 q = l + x;                 for (let i = p; i <= q; i++)                     document.write(i+" ");             }                      // If array size to be constructed is even             else {                 l = n / 2;                 p = x - l;                 q = x + l;                 for (let i = p; i <= q; i++) {                     if (i !== x)                         document.write(i+" ");                 }             }         }                  // Driver code         let N = 4;         let X = 8;                  // Function call         findArray(N, X);                  // This code is contributed by ashishsingh13122000.         </script> 

Output
6 7 9 10 

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


Next Article
Min difference between maximum and minimum element in all Y size subarrays

S

sachinupreti190
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Minimum difference between max and min of all K-size subsets
    Given an array of integer values, we need to find the minimum difference between the maximum and minimum of all possible K-length subsets. Examples : Input : arr[] = [3, 5, 100, 101, 102] K = 3 Output : 2 Explanation : Possible subsets of K-length with their differences are, [3 5 100] max min diff i
    7 min read
  • Split a given array into K subarrays minimizing the difference between their maximum and minimum
    Given a sorted array arr[] of N integers and an integer K, the task is to split the array into K subarrays such that the sum of the difference of maximum and minimum element of each subarray is minimized. Examples: Input: arr[] = {1, 3, 3, 7}, K = 4 Output: 0 Explanation: The given array can be spli
    6 min read
  • Minimum difference between maximum and minimum value of Array with given Operations
    Given an array arr[] and an integer K. The following operations can be performed on any array element: Multiply the array element with K.If the element is divisible by K, then divide it by K. The above two operations can be applied any number of times including zero on any array element. The task is
    9 min read
  • k size subsets with maximum difference d between max and min
    C/C++ Code // C++ code to find no. of subsets with // maximum difference d between max and #include <bits/stdc++.h> using namespace std; // function to calculate factorial of a number int fact(int i) { if (i == 0) return 1; return i * fact(i - 1); } int ans(int a[], int n, int k, int x) { if (
    15+ min read
  • Min difference between maximum and minimum element in all Y size subarrays
    Given an array arr[] of size N and integer Y, the task is to find a minimum of all the differences between the maximum and minimum elements in all the sub-arrays of size Y. Examples: Input: arr[] = { 3, 2, 4, 5, 6, 1, 9 } Y = 3Output: 2Explanation:All subarrays of length = 3 are:{3, 2, 4} where maxi
    15+ min read
  • Split array into K Subarrays to minimize sum of difference between min and max
    Given a sorted array arr[] of size N and integer K, the task is to split the array into K non-empty subarrays such that the sum of the difference between the maximum element and the minimum element of each subarray is minimized. Note: Every element of the array must be included in one subarray and e
    6 min read
  • Minimize difference between maximum and minimum array elements by exactly K removals
    Given an array arr[] consisting of N positive integers and an integer K, the task is to minimize the difference between the maximum and minimum element in the given array after removing exactly K elements. Examples: Input: arr[] = {5, 1, 6, 7, 12, 10}, K = 3Output: 2Explanation:Remove elements 12, 1
    6 min read
  • Minimum distance between the maximum and minimum element of a given Array
    Given an array A[] consisting of N elements, the task is to find the minimum distance between the minimum and the maximum element of the array.Examples: Input: arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2} Output: 3 Explanation: The minimum element(= 1) is present at indices {2, 4} The maximum elemen
    8 min read
  • Minimize difference between maximum and minimum array elements by removing a K-length subarray
    Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum difference between the maximum and minimum element present in the array after removing any subarray of size K. Examples: Input: arr[] = {4, 5, 8, 9, 1, 2}, K = 2Output: 4Explanation: Remove the subarray {
    10 min read
  • Minimize the difference between minimum and maximum elements
    Given an array of [Tex]N [/Tex]integers and an integer [Tex]k [/Tex]. It is allowed to modify an element either by increasing or decreasing them by k (only once).The task is to minimize and print the maximum difference between the shortest and longest towers. Examples: Input: arr[] = {1, 10, 8, 5},
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences