Open In App

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:

  1. For an index i(0 ≤ i < N), replace arr[i] with a and b such that arr[i] = a + b.
  2. For two indices i (0 ≤ i < N) and n (0 ≤ n < N), Replace arr[n] with (arr[i] + arr[n]). Pop arr[i] from the array.

Examples:



Input: arr[] = {1, 4, 2, 8}, N = 4
Output: 5
Explanation: arr[3] can be split into [3, 5] to form arr [] = {1, 4, 2, 3, 5}. 
There is no other way to split this into more elements.

Input: arr[] = {1, 1, 4, 3}, N = 4
Output: 3
Explanation: No operations can be performed to increase the number of distinct elements.



 

Approach: The problem can be based on the following observation:

Using the second operation, the entire arr[] can be reduced to 1 element, such that arr[0] = sum(arr[]). Now, the array sum can be partitioned into maximum number of unique parts get maximum unique elements. 

Follow the below steps to implement the observation:

Below is the implementation of the above approach.




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum possible
// number of unique elements
int maxUniqueElems(int* Arr, int L)
{
    // Initializing sums variable
    int sums = 0;
 
    // Calculating sum of array
    for (int j = 0; j < L; j++)
        sums += Arr[j];
 
    // Initializing i to count total number of
    // distinct elements
    int i = 1;
 
    // Looping till sums becomes 0
    while (sums > 0) {
 
        // Subtracting i from sums and
        // incrementing i
        sums -= i;
        i++;
    }
 
    // Returning the result
    return i - 1;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 4, 2, 8 };
    int N = 4;
 
    // Function call
    cout << maxUniqueElems(arr, N);
    return 0;
}




// JAVA code to implement the above approach
 
import java.util.*;
class GFG
{
   
    // Function to calculate the maximum possible
    // number of unique elements
    public static int maxUniqueElems(int []Arr, int L)
    {
        // Initializing sums variable
        int sums = 0;
     
        // Calculating sum of array
        for (int j = 0; j < L; j++)
            sums += Arr[j];
     
        // Initializing i to count total number of
        // distinct elements
        int i = 1;
     
        // Looping till sums becomes 0
        while (sums > 0) {
     
            // Subtracting i from sums and
            // incrementing i
            sums -= i;
            i++;
        }
     
        // Returning the result
        return i - 1;
    }
     
    // Driver code
    public static void main(String []args)
    {
        int arr[] = new int[]{ 1, 4, 2, 8 };
        int N = 4;
     
        // Function call
        System.out.println(maxUniqueElems(arr, N));
    }
}
 
// This code is contributed by Taranpreet




# python3 code to implement the above approach
 
# Function to calculate the maximum possible
# number of unique elements
def maxUniqueElems(Arr, L):
 
    # Initializing sums variable
    sums = 0
 
    # Calculating sum of array
    for j in range(0, L):
        sums += Arr[j]
 
    # Initializing i to count total number of
    # distinct elements
    i = 1
 
    # Looping till sums becomes 0
    while (sums > 0):
 
        # Subtracting i from sums and
        # incrementing i
        sums -= i
        i += 1
 
    # Returning the result
    return i - 1
 
# Driver code
if __name__ == "__main__":
 
    arr = [1, 4, 2, 8]
    N = 4
 
    # Function call
    print(maxUniqueElems(arr, N))
 
    # This code is contributed by rakeshsahni




<script>
 
// JavaScript code to implement the above approach
 
// Function to calculate the maximum possible
// number of unique elements
function maxUniqueElems(Arr, L){
 
    // Initializing sums variable
    let sums = 0
 
    // Calculating sum of array
    for(let j = 0; j < L; j++)
        sums += Arr[j]
 
    // Initializing i to count total number of
    // distinct elements
    let i = 1
 
    // Looping till sums becomes 0
    while (sums > 0){
 
        // Subtracting i from sums and
        // incrementing i
        sums -= i
        i += 1
    }
 
    // Returning the result
    return i - 1
}
 
// Driver code
let arr = [1, 4, 2, 8]
let N = 4
 
// Function call
document.write(maxUniqueElems(arr, N),"</br>")
 
// This code is contributed by shinjanpatra
 
</script>




// C# code to implement the above approach
 
using System;
class GFG {
 
  // Function to calculate the maximum possible
  // number of unique elements
  static int maxUniqueElems(int[] Arr, int L)
  {
    // Initializing sums variable
    int sums = 0;
 
    // Calculating sum of array
    for (int j = 0; j < L; j++)
      sums += Arr[j];
 
    // Initializing i to count total number of
    // distinct elements
    int i = 1;
 
    // Looping till sums becomes 0
    while (sums > 0) {
 
      // Subtracting i from sums and
      // incrementing i
      sums -= i;
      i++;
    }
 
    // Returning the result
    return i - 1;
  }
 
  // Driver code
  public static void Main()
  {
    int[] arr = { 1, 4, 2, 8 };
    int N = 4;
 
    // Function call
    Console.WriteLine(maxUniqueElems(arr, N));
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Output
5

Time Complexity: O(max(N, sqrt(S))) where S is the sum of array
Auxiliary Space: O(1)

Another Approach:

  1. First, the necessary header file is included using the #include preprocessor directive. The bits/stdc++.h header file includes all standard library header files, making it easier to write code.
  2. The maxUniqueElems() function takes an integer array (Arr) and its length (L) as input arguments.
  3. The variable “sums” is initialized to 0.
  4. The for loop is used to calculate the sum of all elements of the input array. It iterates over each element of the array using the loop variable “j”, and adds the value of the element to the “sums” variable.
  5. The next step is to calculate the total number of distinct elements in the input array. This is done using the formula:                                                      i = (sqrt(8*sums + 1) – 1) / 2                                                                                                                                                                                                 The formula is derived from the quadratic equation: n(n+1)/2 = sums, where n is the number of distinct elements. Solving the equation for n gives the above formula.
  6. Finally, the maxUniqueElems() function returns the value of “i”.

Below is the implementation of the above approach:




#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum possible
// number of unique elements
int maxUniqueElems(int* Arr, int L)
{
    // Initializing sums variable
    int sums = 0;
 
    // Calculating sum of array
    for (int j = 0; j < L; j++)
        sums += Arr[j];
 
    // Initializing i to count total number of
    // distinct elements
    int i = (sqrt(8*sums + 1) - 1) / 2;
 
    // Returning the result
    return i;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 4, 2, 8 };
    int N = 4;
 
    // Function call
    cout << maxUniqueElems(arr, N);
    return 0;
}




import java.util.*;
 
public class Main {
 
    // Function to calculate the maximum possible
    // number of unique elements
    static int maxUniqueElems(int[] Arr, int L) {
        // Initializing sums variable
        int sums = 0;
 
        // Calculating sum of array
        for (int j = 0; j < L; j++)
            sums += Arr[j];
 
        // Initializing i to count total number of
        // distinct elements
        int i = (int) ((Math.sqrt(8 * sums + 1) - 1) / 2);
 
        // Returning the result
        return i;
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {1, 4, 2, 8};
        int N = 4;
 
        // Function call
        System.out.println(maxUniqueElems(arr, N));
    }
}




import math
 
# Function to calculate the maximum possible
# number of unique elements
def maxUniqueElems(Arr, L):
    # Initializing sums variable
    sums = 0
 
    # Calculating sum of array
    for j in range(L):
        sums += Arr[j]
 
    # Initializing i to count total number of
    # distinct elements
    i = (int(math.sqrt(8*sums + 1)) - 1) // 2
 
    # Returning the result
    return i
 
# Driver code
if __name__ == '__main__':
    arr = [1, 4, 2, 8]
    N = 4
 
    # Function call
    print(maxUniqueElems(arr, N))




using System;
 
public class GFG {
 
    // Function to calculate the maximum possible
    // number of unique elements
    static int maxUniqueElems(int[] Arr, int L) {
        // Initializing sums variable
        int sums = 0;
 
        // Calculating sum of array
        for (int j = 0; j < L; j++)
            sums += Arr[j];
 
        // Initializing i to count total number of
        // distinct elements
        int i = (int) ((Math.Sqrt(8 * sums + 1) - 1) / 2);
 
        // Returning the result
        return i;
    }
 
    // Driver code
    public static void Main() {
        int[] arr = {1, 4, 2, 8};
        int N = 4;
 
        // Function call
        Console.Write(maxUniqueElems(arr, N));
    }
}




function maxUniqueElems(arr) {
  // Initializing sums variable
  let sums = 0;
 
  // Calculating sum of array
  for (let j = 0; j < arr.length; j++) {
    sums += arr[j];
  }
 
  // Initializing i to count total number of distinct elements
  let i = Math.floor((Math.sqrt(8 * sums + 1) - 1) / 2);
 
  // Returning the result
  return i;
}
 
// Driver code
const arr = [1, 4, 2, 8];
console.log(maxUniqueElems(arr)); // Output: 3

Output
5

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


Article Tags :