Maximize removals of balls of at least two different types
Last Updated :
24 Jun, 2021
Given an array arr[] of size 3 denoting the number of balls of type 1, 2, and 3 respectively, the task is to find the maximum number of moves that can be performed if in one move, three balls, out of which at least 2 balls of different types, are removed.
Examples:
Input: arr[] = {2, 3, 3}
Output: 2
Explanation:
Move 1: Remove 1 ball of each type. Therefore, arr[] becomes {1, 2, 2}.
Move 2: Remove 1 ball of each type. Therefore, arr[] becomes {0, 1, 1}.
No further moves can be performed.
Input: arr[] = {100, 1, 2}
Output: 3
Explanation:
Move 1: Remove 1 ball of type 2 and 2 balls of type 1. Therefore, arr[] becomes {98, 0, 2}.
Move 2: Remove 1 ball of type 3 and 2 balls of type 1. Therefore, arr[] becomes {96, 0, 1}.
Move 3: Remove 1 ball of type 3 and 2 balls of type 1. Therefore, arr[] becomes {94, 0, 0}.
No further moves can be performed.
Approach: The idea to sort the array in increasing order and then arises two cases:
- If arr[2] is smaller than 2 * (arr[0] + arr[1]), the answer will be (arr[0] + arr[1] + arr[2]) / 3.
- If arr[2] is greater than 2 * (arr[0] + arr[1]), the answer will be arr[0] + arr[1].
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 findMoves( int arr[])
{
sort(arr, arr + 3);
cout << (min(arr[0] + arr[1],
(arr[0] + arr[1] + arr[2]) / 3));
}
int main()
{
int arr[3] = { 2, 3, 3 };
findMoves(arr);
return 0;
}
|
Java
import java.util.Arrays;
class GFG{
static void findMoves( int arr[])
{
Arrays.sort(arr);
System.out.println(Math.min(arr[ 0 ] + arr[ 1 ],
(arr[ 0 ] + arr[ 1 ] +
arr[ 2 ]) / 3 ));
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 3 };
findMoves(arr);
}
}
|
Python3
def findMoves(arr):
arr = sorted (arr)
print ( min (arr[ 0 ] + arr[ 1 ],
(arr[ 0 ] + arr[ 1 ] +
arr[ 2 ]) / / 3 ))
if __name__ = = '__main__' :
arr = [ 2 , 3 , 3 ]
findMoves(arr)
|
C#
using System;
class GFG
{
static void findMoves( int []arr)
{
Array.Sort(arr);
Console.Write(Math.Min(arr[0] + arr[1],
(arr[0] + arr[1] +
arr[2]) / 3));
}
public static void Main(String[] args)
{
int []arr = { 2, 3, 3 };
findMoves(arr);
}
}
|
Javascript
<script>
function findMoves(arr) {
arr.sort( function (a, b) { return a - b; })
document.write(Math.min(arr[0] + arr[1],
parseInt((arr[0] + arr[1] + arr[2]) / 3)));
}
let arr = [2, 3, 3];
findMoves(arr);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...