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:
Maximize count of distinct elements in a subsequence of size K in given array
Next article icon

Maximize count of distinct elements possible in an Array from the given operation

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

Given an array A[] of size N, the task is to maximize the count of distinct elements in the array by inserting the absolute differences of the existing array elements.

Examples: 

Input: A[] = {1, 2, 3, 5} 
Output: 5 
Explanation: 
Possible absolute differences among the array elements are: 
(2 – 1) = 1 
(5 – 3) = 2 
(5 – 2) = 3 
(5 – 1) = 4 
Hence, inserting 4 into the array maximizes the count of distinct elements.
Input: A[] = {1, 2, 3, 6} 
Output: 6  

Naive Approach: 
Generate all possible pairs from the array and store their absolute differences in a set. Insert all the array elements into the set. The final size of the set denotes the maximum distinct elements that the array can possess after performing given operations. 
Time Complexity: O(N2) 
Auxiliary Space: O(N)
Efficient Approach: 
Follow the steps below to optimize the above approach:  

  1. Find the maximum element of the array.The maximum possible absolute difference of any two elements does not exceed the maximum element of the array. 
     
  2. Calculate the GCD of the array, since it is the common factor of the whole array. 
     
  3. Divide the maximum element with the gcd of the array to get the count of the distinct elements. 
     

Below is the implementation of the above approach:
 

C++




// C++ program to find the maximum
// possible distinct elements that
// can be obtained from the array
// by performing the given operations
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the gcd
// of two numbers
int gcd(int x, int y)
{
    if (x == 0)
        return y;
    return gcd(y % x, x);
}
 
// Function to calculate and return
// the count of maximum possible
// distinct elements in the array
int findDistinct(int arr[], int n)
{
    // Find the maximum element
    int maximum = *max_element(arr,
                               arr + n);
 
    // Base Case
    if (n == 1)
        return 1;
 
    if (n == 2) {
        return (maximum / gcd(arr[0],
                              arr[1]));
    }
 
    // Finding the gcd of first
    // two element
    int k = gcd(arr[0], arr[1]);
 
    // Calculate Gcd of the array
    for (int i = 2; i < n; i++) {
        k = gcd(k, arr[i]);
    }
 
    // Return the total count
    // of distinct elements
    return (maximum / k);
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << findDistinct(arr, n);
    return 0;
}
 
 

Java




// Java program to find the maximum
// possible distinct elements that
// can be obtained from the array
// by performing the given operations
import java.util.*;
 
class GFG{
     
// Function to find the gcd
// of two numbers
static int gcd(int x, int y)
{
    if (x == 0)
        return y;
    return gcd(y % x, x);
}
 
// Function to calculate and return
// the count of maximum possible
// distinct elements in the array
static int findDistinct(int arr[], int n)
{
     
    // Find the maximum element
    int maximum = Arrays.stream(arr).max().getAsInt();
 
    // Base Case
    if (n == 1)
        return 1;
 
    if (n == 2)
    {
        return (maximum / gcd(arr[0],
                              arr[1]));
    }
 
    // Finding the gcd of first
    // two element
    int k = gcd(arr[0], arr[1]);
 
    // Calculate Gcd of the array
    for(int i = 2; i < n; i++)
    {
        k = gcd(k, arr[i]);
    }
 
    // Return the total count
    // of distinct elements
    return (maximum / k);
}
 
// Driver code
public static void main (String[] args)
{
    int arr[] = { 1, 2, 3, 5 };
    int n = arr.length;
 
    System.out.println(findDistinct(arr, n));
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 program to find the maximum
# possible distinct elements that
# can be obtained from the array
# by performing the given operations
 
# Function to find the gcd
# of two numbers
def gcd(x, y):
     
    if (x == 0):
        return y
    return gcd(y % x, x)
 
# Function to calculate and return
# the count of maximum possible
# distinct elements in the array
def findDistinct(arr, n):
     
    # Find the maximum element
    maximum = max(arr)
     
    # Base Case
    if (n == 1):
        return 1
 
    if (n == 2):
        return (maximum // gcd(arr[0],
                               arr[1]))
 
    # Finding the gcd of first
    # two element
    k = gcd(arr[0], arr[1])
 
    # Calculate Gcd of the array
    for i in range(2, n):
        k = gcd(k, arr[i])
 
    # Return the total count
    # of distinct elements
    return (maximum // k)
 
# Driver Code
if __name__ == '__main__':
 
    arr = [ 1, 2, 3, 5 ]
    n = len(arr)
 
    print(findDistinct(arr, n))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program to find the maximum
// possible distinct elements that
// can be obtained from the array
// by performing the given operations
using System;
using System.Linq;
class GFG{
 
// Function to find the gcd
// of two numbers
static int gcd(int x, int y)
{
    if (x == 0)
        return y;
    return gcd(y % x, x);
}
 
// Function to calculate and return
// the count of maximum possible
// distinct elements in the array
static int findDistinct(int []arr, int n)
{
    // Find the maximum element
    int maximum = arr.Max();
 
    // Base Case
    if (n == 1)
        return 1;
 
    if (n == 2)
    {
        return (maximum / gcd(arr[0],
                              arr[1]));
    }
 
    // Finding the gcd of first
    // two element
    int k = gcd(arr[0], arr[1]);
 
    // Calculate Gcd of the array
    for (int i = 2; i < n; i++)
    {
        k = gcd(k, arr[i]);
    }
 
    // Return the total count
    // of distinct elements
    return (maximum / k);
}
 
// Driver Code
public static void Main()
{
    int []arr = { 1, 2, 3, 5 };
    int n = arr.Length;
 
    Console.Write(findDistinct(arr, n));
}
}
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
 
// Javascript program to find the maximum
// possible distinct elements that
// can be obtained from the array
// by performing the given operations
 
// Function to find the gcd
// of two numbers
function gcd(x, y)
{
    if (x == 0)
        return y;
    return gcd(y % x, x);
}
   
// Function to calculate and return
// the count of maximum possible
// distinct elements in the array
function findDistinct(arr, n)
{
       
    // Find the maximum element
    let maximum = Math.max(...arr);
   
    // Base Case
    if (n == 1)
        return 1;
   
    if (n == 2)
    {
        return (maximum / gcd(arr[0],
                              arr[1]));
    }
   
    // Finding the gcd of first
    // two element
    let k = gcd(arr[0], arr[1]);
   
    // Calculate Gcd of the array
    for(let i = 2; i < n; i++)
    {
        k = gcd(k, arr[i]);
    }
   
    // Return the total count
    // of distinct elements
    return (maximum / k);
}
 
// Driver Code
     
    let arr = [ 1, 2, 3, 5 ];
    let n = arr.length;
   
    document.write(findDistinct(arr, n));
 
</script>
 
 
Output: 
5

 

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



Next Article
Maximize count of distinct elements in a subsequence of size K in given array

D

dazzling_coder
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • cpp-set
  • GCD-LCM
  • number-theory
Practice Tags :
  • Arrays
  • Mathematical
  • number-theory

Similar Reads

  • Maximize count of distinct elements in a subsequence of size K in given array
    Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are
    4 min read
  • Count ways to fill Array with distinct elements with given limitation
    Given an array arr[] of size N and you need to fill another empty array of size N with positive integers. Each element in the given array denotes the maximum positive integer you can choose to fill the empty array. The task is to find the number of ways to fill the empty array such that all elements
    6 min read
  • Maximize count of corresponding same elements in given Arrays by Rotation
    Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples: Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9,
    8 min read
  • Maximize minimum distance between repetitions from any permutation of the given Array
    Given an array arr[], consisting of N positive integers in the range [1, N], the task is to find the largest minimum distance between any consecutive repetition of an element from any permutation of the given array. Examples: Input: arr[] = {1, 2, 1, 3} Output: 3 Explanation: The maximum possible di
    5 min read
  • Maximize the count of distinct elements in Array after at most K changes
    Given an array arr[], the task is to find the maximum number of distinct numbers in arr after at most K changes. In each change pick any element X from arr and change it to Y such that L <= Y <= R. Examples: Input: arr[] = {1, 2, 1, 4, 6, 4, 4}, L = 1, R = 5 and K = 2Output: 6Explanation: Foll
    8 min read
  • Minimize operations to make all the elements of given Subarrays distinct
    Given an arr[] of positive integers and start[] and end[] arrays of length L, Which contains the start and end indexes of L number of non-intersecting sub-arrays as a start[i] and end[i] for all (1 ? i ? L). An operation is defined as below: Select an ordered continuous or non - continuous part of t
    11 min read
  • Maximize first array element by performing given operations at most K times
    Given an array arr[] of size N an integer K, the task is to find the maximize the first element of the array by performing the following operations at most K times: Choose a pair of indices i and j (0 ? i, j ? N-1) such that |i ? j| = 1 and arri > 0.Set arri = arri ? 1 and arrj = arrj + 1 on thos
    7 min read
  • Maximize the last Array element as per the given conditions
    Given an array arr[] consisting of N integers, rearrange the array such that it satisfies the following conditions: arr[0] must be 1.Difference between adjacent array elements should not exceed 1, that is, arr[i] - arr[i-1] ? 1 for all 1 ? i < N. The permissible operations are as follows: Rearran
    5 min read
  • Maximize sum of array elements removed by performing the given operations
    Given two arrays arr[] and min[] consisting of N integers and an integer K. For each index i, arr[i] can be reduced to at most min[i]. Consider a variable, say S(initially 0). The task is to find the maximum value of S that can be obtained by performing the following operations: Choose an index i an
    8 min read
  • Maximize distinct elements of Array by combining two elements or splitting an element
    Given an array arr[] of length N, the task is to maximize the number of distinct elements in the array by performing either of the following operations, any number of times: For an index i(0 ≤ i < N), replace arr[i] with a and b such that arr[i] = a + b.For two indices i (0 ≤ i < N) and n (0 ≤
    9 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