📌  相关文章
📜  最大限度地去除至少两种不同类型的球

📅  最后修改于: 2022-05-13 01:56:08.778000             🧑  作者: Mango

最大限度地去除至少两种不同类型的球

给定一个大小为3的数组arr[] ,分别表示类型1、23的球的数量,任务是找到如果在一次移动中有三个球时可以执行的最大移动数,其中在至少 2 个不同类型的球被移除。

例子:

方法:按递增顺序对数组进行排序然后出现两种情况的想法:

  • 如果arr[2]小于2 * (arr[0] + arr[1]) ,答案将是(arr[0] + arr[1] + arr[2]) / 3
  • 如果arr[2]大于2 * (arr[0] + arr[1]) ,答案将是arr[0] + arr[1]

请按照以下步骤解决问题:

  • 按升序对数组进行排序。
  • 打印(arr[0]+arr[1]+arr[2])/3arr[0]+arr[1]的最小值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find maximum moves that
// can be performed if in each move 3
// balls of different types are removed
void findMoves(int arr[])
{
    // Sort the array in increasing order
    sort(arr, arr + 3);
 
    // Print the answer
    cout << (min(arr[0] + arr[1],
                 (arr[0] + arr[1] + arr[2]) / 3));
}
 
// Driver Code
int main()
{
    // Given Input
    int arr[3] = { 2, 3, 3 };
 
    // Function Call
    findMoves(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.Arrays;  
 
class GFG{
     
// Function to find maximum moves that
// can be performed if in each move 3
// balls of different types are removed
static void findMoves(int arr[])
{
     
    // Sort the array in increasing order
    Arrays.sort(arr);
 
    // Print the answer
    System.out.println(Math.min(arr[0] + arr[1],
                               (arr[0] + arr[1] +
                                arr[2]) / 3));
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Input
    int arr[] = { 2, 3, 3 };
 
    // Function Call
    findMoves(arr);
}
}
 
// This code is contributed by AnkThon


Python3
# Python3 program for the above approach
 
# Function to find maximum moves that
# can be performed if in each move 3
# balls of different types are removed
def findMoves(arr):
     
    # Sort the array in increasing order
    arr = sorted(arr)
 
    # Print the answer
    print (min(arr[0] + arr[1],
              (arr[0] + arr[1] +
               arr[2]) // 3))
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    arr = [ 2, 3, 3 ]
 
    # Function Call
    findMoves(arr)
 
# This code is contributed by mohit kumar 29


C#
// Java program for the above approach
using System;  
class GFG
{
     
// Function to find maximum moves that
// can be performed if in each move 3
// balls of different types are removed
static void findMoves(int []arr)
{
     
    // Sort the array in increasing order
    Array.Sort(arr);
 
    // Print the answer
    Console.Write(Math.Min(arr[0] + arr[1],
                               (arr[0] + arr[1] +
                                arr[2]) / 3));
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given Input
    int []arr = { 2, 3, 3 };
 
    // Function Call
    findMoves(arr);
}
}
 
// This code is contributed by shivanisinghss2110


Javascript


输出:
2

时间复杂度: O(1)
辅助空间: O(1)