Maximum array elements that can be removed along with its adjacent values to empty given array
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: 4
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:
- 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 <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
// 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
# 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
<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>
Time Complexity: O(N * Log(N))
Space Complexity: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read