Skip to content
Related Articles
Maximum array elements that can be removed along with its adjacent values to empty given array
• Difficulty Level : Easy
• Last Updated : 17 May, 2021

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 modifies the array arr[] = {5, 3, 6, 7, 4}.
Picking the coin coins modifies the array arr[] = {5, 6, 7}
Picking the coin coins modifies the array arr[] = {7}
Picking the coin coins 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:

• Initialize a variable, say cntSteps to store the maximum count of steps required to remove all the coins from the arr[] array.
• Create a map, say Map to store the frequency of elements of the arr[] array in ascending order.
• Initialize a variable, say Min to store the smallest element of the Map.
• Traverse the Map and in each traversal remove the Min and (Min + 1) from Map and also increment the value of cntSteps by 1.
• Finally, print the value of cntSteps.

Below is the implementation of the above approach :

## C++

 `// C++ program to implement``// the above approach`` ` `#include ``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);``    ``cout << maximumSteps(arr, N);``    ``return` `0;``}`

## Java

 `// 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 mp = ``new` `HashMap();``     ` `    ``// 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 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

 `# 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#

 `// 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`

## Javascript

 ``
Output:
`4`

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

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 industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up