Open In App

Maximum array elements that can be removed along with its adjacent values to empty given array

Given an array arr[] of size N. In each operation, pick an array element X and remove all array elements in the range [X – 1, X + 1]. The task is to find the maximum number of steps required such that no coins left in the array.

Examples:



Input: coins [] = {5, 1, 3, 2, 6, 7, 4} 
Output:
Explanation: 
Picking the coin coins[1] modifies the array arr[] = {5, 3, 6, 7, 4}. 
Picking the coin coins[1] modifies the array arr[] = {5, 6, 7} 
Picking the coin coins[0] modifies the array arr[] = {7} 
Picking the coin coins[0] modifies the array arr[] = {}. Therefore, the required output is 4.

Input: coins [] = {6, 7, 5, 1} 
Output: 3



Naive Approach: The simplest approach to solve this problem is to generate all possible permutation of the given array and for each permutation of the array, find the number of steps required to remove all the elements of the array by picking only the first element of the array in all possible step. Finally, print the maximum number of steps required to remove all the elements.

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

Efficient approach: To optimize the above approach the idea is to pick an element from the array in such a way that in each step at most two elements from the array will be removed. Follow the steps below to solve the problem:

Below is the implementation of the above approach :




// C++ program to implement
// the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
  
// Function to find maximum steps to
// remove all coins from the arr[]
int maximumSteps(int arr[], int N)
{
      
    // Store the frequency of array
    // elements in ascending order
    map<int, int> Map;
      
      
    // Traverse the arr[] array
    for (int i = 0; i < N; i++) {
        Map[arr[i]]++;
    }
      
      
    // Stores count of steps required
    // to remove all the array elements
    int cntSteps = 0;
      
      
    // Traverse the map
    for (auto i : Map) {
          
        // Stores the smallest element
        // of Map
        int X = i.first;
          
        // If frequency if X
        // greater than 0
        if (i.second > 0) {
              
            // Update cntSteps
            cntSteps++;
              
              
            // Mark X as
            // removed element
            Map[X] = 0;
             
             
            // If frequency of (X + 1)
            // greater than  0
            if (Map[X + 1])
                  
                  
                // Mark (X + 1) as
                // removed element
                Map[X + 1] = 0;
        }
    }
    return cntSteps;
}
  
  
// Driver Code
int main()
{
    int arr[] = { 5, 1, 3, 2, 6, 7, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << maximumSteps(arr, N);
    return 0;
}




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
// Function to find maximum steps to
// remove all coins from the arr[]
static int maximumSteps(int arr[], int N)
{
     
    // Store the frequency of array
    // elements in ascending order
    Map<Integer,
        Integer> mp = new HashMap<Integer,
                                  Integer>();
      
    // Traverse the arr[] array
    for(int i = 0; i < N; i++)
    {
        mp.put(arr[i],
               mp.getOrDefault(arr[i], 0) + 1);
    }
     
    // Stores count of steps required
    // to remove all the array elements
    int cntSteps = 0;
     
    // Traverse the mp
    for(Map.Entry<Integer, Integer> it : mp.entrySet())
    {
         
        // Stores the smallest element
        // of mp
        int X = it.getKey();
         
        // If frequency if X
        // greater than 0
        if (it.getValue() > 0)
        {
             
            // Update cntSteps
            cntSteps++;
             
            // Mark X as
            // removed element
            mp.replace(X, 0);
             
            // If frequency of (X + 1)
            // greater than  0
            if (mp.getOrDefault(X + 1, 0) != 0)
                  
                // Mark (X + 1) as
                // removed element
                mp.replace(X + 1, 0);
        }
    }
    return cntSteps;
}
  
// Driver Code
public static void main(String args[])
{
    int arr[] = { 5, 1, 3, 2, 6, 7, 4 };
    int N = arr.length;
     
    System.out.print(maximumSteps(arr, N));
}
}
  
// This code is contributed by ipg2016107




# Python3 program to implement
# the above approach
 
# Function to find maximum steps to
# remove all coins from the arr[]
def maximumSteps(arr, N):
     
    # Store the frequency of array
    # elements in ascending order
    Map = {}
     
    # Traverse the arr[] array
    for i in range(N):
        Map[arr[i]] = Map.get(arr[i], 0) + 1
         
    # Stores count of steps required
    # to remove all the array elements
    cntSteps = 0
 
    # Traverse the map
    for i in Map:
         
        # Stores the smallest element
        # of Map
        X = i
 
        # If frequency if X
        # greater than 0
        if (Map[i] > 0):
             
            # Update cntSteps
            cntSteps += 1
             
            # Mark X as
            # removed element
            Map[X] = 0
             
            # If frequency of (X + 1)
            # greater than  0
            if (X + 1 in Map):
                 
                # Mark (X + 1) as
                # removed element
                Map[X + 1] = 0
 
    return cntSteps
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 5, 1, 3, 2, 6, 7, 4 ]
    N = len(arr)
     
    print(maximumSteps(arr, N))
 
# This code is contributed by mohit kumar 29




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find maximum steps to
// remove all coins from the []arr
static int maximumSteps(int []arr, int N)
{
   
    // Store the frequency of array
    // elements in ascending order
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
      
    // Traverse the []arr array
    for(int i = 0; i < N; i++)
    {
        if (mp.ContainsKey(arr[i]))
        {
            mp[arr[i]]++;   
        }
        else
        {
            mp.Add(arr[i], 1);
        }
    }
     
    // Stores count of steps required
    // to remove all the array elements
    int cntSteps = 0;
      
    // Traverse the mp
    foreach(KeyValuePair<int, int> it in mp)
    {
         
        // Stores the smallest element
        // of mp
        int X = it.Key;
         
        // If frequency if X
        // greater than 0
        if (it.Value > 0)
        {
             
            // Update cntSteps
            cntSteps++;
          
        }
    }
    return (cntSteps + 1) / 2;
}
  
// Driver Code
public static void Main(String []args)
{
    int []arr = { 5, 1, 3, 2, 6, 7, 4 };
    int N = arr.Length;
     
    Console.Write(maximumSteps(arr, N));
}
}
  
// This code is contributed by Princi Singh




<script>
 
// Javascript program to implement
// the above approach
  
  
// Function to find maximum steps to
// remove all coins from the arr[]
function maximumSteps(arr, N)
{
      
    // Store the frequency of array
    // elements in ascending order
    var map = new Map();
      
      
    // Traverse the arr[] array
    for (var i = 0; i < N; i++) {
        if(map.has(arr[i]))
        {
            map.set(arr[i], map.get(arr[i])+1);
        }
        else
        {
            map.set(arr[i], 1);
        }
    }
      
      
    // Stores count of steps required
    // to remove all the array elements
    var cntSteps = 0;
      
      
    // Traverse the map
    map.forEach((value, key) => {
          
        // Stores the smallest element
        // of map
        var X = key;
          
        // If frequency if X
        // greater than 0
        if (value > 0) {
              
            // Update cntSteps
            cntSteps++;
              
              
            // Mark X as
            // removed element
            map.set(X, 0);
             
             
            // If frequency of (X + 1)
            // greater than  0
            if (map.has(X + 1))
                  
                  
                // Mark (X + 1) as
                // removed element
                map.set(X+1, 0);
        }
    });
 
    return cntSteps;
}
  
  
// Driver Code
var arr = [5, 1, 3, 2, 6, 7, 4];
var N = arr.length;
document.write( maximumSteps(arr, N));
 
</script>

Output: 
4

 

Time Complexity: O(N * Log(N)) 
Space Complexity: O(N)


Article Tags :