Minimize consecutive removals of elements of the same type to empty given array
Last Updated :
21 Apr, 2021
Given an array A[ ] consisting of N positive integers, such that each array element Ai denotes the count of elements of ith type, the task is to minimize the number of deletions of consecutive elements of the same type to empty the given array.
Examples:
Input : A[ ] = {3, 3, 2}
Output: 0
Explanation: The array consists of 3, 3, 2 elements of 1st, 2nd and 3rd type respectively. By removing the array elements in the order {2, 1, 2, 3, 1, 3, 1}, a sequence is obtained in which no two consecutive elements are removed which are of the same type. Therefore, the count is 0.
Input: A [ ] = {1, 4, 1}
Output: 1
Explanation: The array consists of 1, 4, 1 elements of 1st, 2nd and 3rd type respectively. By removing the array elements in the order { 2, 3, 2, 2, 1, 2}, consecutive deletions of same type elements is reduced to 1. Therefore, the count is 1.
Approach: The problem can be solved by Greedy Approach. Follow the steps below to solve the problem:
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void minRemovals( int A[], int N)
{
sort(A, A + N);
int mx = A[N - 1];
int sum = 1;
for ( int i = 0; i < N; i++) {
sum += A[i];
}
if (sum - mx >= mx) {
cout << 0 << "\n" ;
}
else {
cout << 2 * mx - sum << "\n" ;
}
}
int main()
{
int A[] = { 3, 3, 2 };
int N = sizeof (A) / sizeof (A[0]);
minRemovals(A, N);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static void minRemovals( int []A, int N)
{
Arrays.sort(A);
int mx = A[N - 1 ];
int sum = 1 ;
for ( int i = 0 ; i < N; i++)
{
sum += A[i];
}
if (sum - mx >= mx) {
System.out.println( 0 );
}
else {
System.out.println( 2 * mx - sum);
}
}
public static void main(String[] args) {
int []A = { 3 , 3 , 2 };
int N = A.length;
minRemovals(A, N);
}
}
|
Python3
def minRemovals(A, N):
A.sort()
mx = A[N - 1 ]
sum = 1
for i in range ( 0 , N):
sum + = A[i]
if (( sum - mx) > = mx):
print ( 0 , end = "")
else :
print ( 2 * mx - sum , end = "")
if __name__ = = "__main__" :
A = [ 3 , 3 , 2 ]
N = len (A)
minRemovals(A, N)
|
C#
using System;
class GFG
{
static void minRemovals( int []A, int N)
{
Array.Sort(A);
int mx = A[N - 1];
int sum = 1;
for ( int i = 0; i < N; i++)
{
sum += A[i];
}
if (sum - mx >= mx)
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(2 * mx - sum);
}
}
public static void Main(String[] args)
{
int []A = { 3, 3, 2 };
int N = A.Length;
minRemovals(A, N);
}
}
|
Javascript
<script>
function minRemovals(A, N)
{
A.sort();
let mx = A[N - 1];
let sum = 1;
for (let i = 0; i < N; i++)
{
sum += A[i];
}
if (sum - mx >= mx) {
document.write(0);
}
else {
document.write(2 * mx - sum);
}
}
let A = [3, 3, 2 ];
let N = A.length;
minRemovals(A, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...