Skip to content
Related Articles

Related Articles

Improve Article

Maximize distinct elements by incrementing/decrementing an element or keeping it same

  • Last Updated : 15 Jun, 2020

Given an array arr[] of N elements, the task is to maximize the count of distinct elements in the array, by either of the given operation on each element of the array:

  • either increasing the element by 1
  • or decreasing the element by 1
  • or keeping the element as it is.

Note: No element can be less than or equal to 0.

Examples:

Input: arr = [4, 4, 5, 5, 5, 5, 6, 6] 
Output:
Explanation: After modification of each element of the array in any of the three possible ways, arr[] = [3, 4, 5, 5, 5, 5, 6, 7]. Here distinct elements are 5. 

Input: arr = [1, 1, 1, 8, 8, 8, 9, 9] 
Output:
Explanation: After modification of each element of the array in any of the three possible ways, arr[] = [1, 1, 2, 7, 8, 8, 9, 10]. Here distinct elements are 6. 
 



Approach: The idea is to sort the given array first, so that the elements can be checked easily, if it is distinct, by comparing with adjacent elements.

  1. First, sort all elements of the array.
  2. Initialize variables count and prev to 0. (To store the count of distinct elements and previous element respectively.)
  3. After that keep a track of the previous element using prev variable.
  4. Iterate the sorted array. 
  5. Decrease the current element’s value by 1 and check if the previous element is lesser than the decreased value. If it is lesser then increment the count and assign current value to prev
  6. If the decreased value of the current element is not greater than the previous element then keep the current element as it is and check if the previous element is lesser than the current element. If it is lesser then increment the count and assign current value to prev
  7. If the current value is not greater than the previous element then increment the current value by 1 and check if the previous element is lesser than the incremented current element. If it is lesser then increment the count and assign current value to prev.
  8. If incremented value of current element is not lesser than previous value then skip that element.
     

Below is the implementation of the above approach:

C++




// C++ program to Maximize distinct
// elements by incrementing/decrementing
// an element or keeping it same
  
#include <bits/stdc++.h>
using namespace std;
  
// Function that Maximize
// the count of distinct
// element
int max_dist_ele(int arr[],
                 int n)
{
  
    // sort thr array
    sort(arr, arr + n);
  
    int ans = 0;
  
    // keeping track of
    // previous change
    int prev = 0;
  
    for (int i = 0;
         i < n; i++) {
  
        // check the
        // decremented value
        if (prev < (arr[i] - 1)) {
  
            ans++;
            prev = arr[i] - 1;
        }
  
        // check the current
        // value
        else if (prev < (arr[i])) {
  
            ans++;
            prev = arr[i];
        }
  
        // check the
        // incremented value
        else if (prev < (arr[i] + 1)) {
  
            ans++;
            prev = arr[i] + 1;
        }
    }
    return ans;
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 1, 1, 8,
                  8, 8, 9, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << max_dist_ele(arr, n)
         << endl;
    return 0;
}

Java




// Java program to Maximize
// the count of distinct element
  
import java.util.*;
  
public class GFG {
  
    // Function that Maximize
    // the count of distinct element
    static int max_dist_ele(
        int arr[], int n)
    {
        // sort thr array
        Arrays.sort(arr);
  
        int ans = 0;
  
        // keeping track of
        // previous change
        int prev = 0;
  
        for (int i = 0;
             i < n; i++) {
  
            // decrement is possible
            if (prev < (arr[i] - 1)) {
  
                ans++;
                prev = arr[i] - 1;
            }
  
            // remain as it is
            else if (prev < (arr[i])) {
  
                ans++;
                prev = arr[i];
            }
            // increment is possible
            else if (prev < (arr[i] + 1)) {
                ans++;
                prev = arr[i] + 1;
            }
        }
  
        return ans;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 1, 1, 1, 8,
                      8, 8, 9, 9 };
        int n = arr.length;
  
        System.out.println(max_dist_ele(arr, n));
    }
}

Python3




# Python3 program to Maximize 
# the count of distinct element
def max_dist_ele(arr, n):
      
    # Sort thr list
    arr.sort()
      
    ans = 0
      
    # Keeping track of 
    # previous change
    prev = 0
      
    for i in range(n):
          
        # Decrement is possible
        if prev < (arr[i] - 1):
            ans += 1;
            prev = arr[i] - 1
              
        # Remain as it is
        elif prev < (arr[i]):
            ans += 1
            prev = arr[i]
              
        # Increment is possible
        elif prev < (arr[i] + 1):
            ans += 1
            prev = arr[i] + 1
      
    return ans
  
# Driver Code
arr = [ 1, 1, 1, 8, 8, 8, 9, 9 ]
n = len(arr)
  
print(max_dist_ele(arr, n))
  
# This code is contributed by rutvik_56

C#




// C# program to maximize the 
// count of distinct element
using System;
  
class GFG{
  
// Function that maximize the 
// count of distinct element
static int max_dist_ele(int []arr, int n)
{
      
    // Sort thr array
    Array.Sort(arr);
  
    int ans = 0;
  
    // Keeping track of
    // previous change
    int prev = 0;
  
    for(int i = 0; i < n; i++)
    {
         
       // Decrement is possible
       if (prev < (arr[i] - 1))
       {
           ans++;
           prev = arr[i] - 1;
       }
         
       // Remain as it is
       else if (prev < (arr[i]))
       {
           ans++;
           prev = arr[i];
       }
         
       // Increment is possible
       else if (prev < (arr[i] + 1))
       {
           ans++;
           prev = arr[i] + 1;
       }
    }
    return ans;
}
  
// Driver Code
public static void Main(String []args)
{
    int []arr = { 1, 1, 1, 8,
                  8, 8, 9, 9 };
    int n = arr.Length;
  
    Console.WriteLine(max_dist_ele(arr, n));
}
}
  
// This code is contributed by Amit Katiyar
Output:
6


Time Complexity: O(N*logN)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :