📌  相关文章
📜  找到获胜玩家的最低健康状况

📅  最后修改于: 2021-04-24 16:24:15             🧑  作者: Mango

给定一个数组health [] ,其中health [i]是游戏中第i玩家的健康,任何玩家都可以攻击游戏中的任何其他玩家。被攻击的玩家的生命值将被攻击者拥有的生命值降低。任务是找到获胜玩家的最低限度的健康状况。

例子:

方法:为了最小化最后一个玩家的生命值,只有生命值较小的玩家才会攻击拥有更大生命值的玩家,如果只有两个玩家参与,那么最后一个玩家的最小生命值就是GCD是两个参与者的初始健康状况。因此,结果将是给定数组的所有元素的GCD。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the minimum possible
// health of the last player
int minHealth(int health[], int n)
{
  
    // Find the GCD of the array elements
    int gcd = 0;
    for (int i = 0; i < n; i++) {
        gcd = __gcd(gcd, health[i]);
    }
  
    return gcd;
}
  
// Driver code
int main()
{
    int health[] = { 5, 6, 1, 2, 3, 4 };
    int n = sizeof(health) / sizeof(int);
  
    cout << minHealth(health, n);
  
    return 0;
}


Java
// Java implementation of the above approach
class GFG
{
  
// Function to return the minimum possible
// health of the last player
static int minHealth(int health[], int n)
{
  
    // Find the GCD of the array elements
    int gcd = 0;
    for (int i = 0; i < n; i++)
    {
        gcd = __gcd(gcd, health[i]);
    }
    return gcd;
}
  
static int __gcd(int a, int b) 
{ 
    return b == 0 ? a : __gcd(b, a % b);     
}
  
// Driver code
public static void main(String []args) 
{
    int health[] = { 5, 6, 1, 2, 3, 4 };
    int n = health.length;
  
    System.out.println(minHealth(health, n));
}
}
  
// This code is contributed by PrinciRaj1992


Python3
# Python3 implementation of the approach 
from math import gcd
  
# Function to return the minimum possible 
# health of the last player 
def minHealth(health, n) :
  
    # Find the GCD of the array elements 
    __gcd = 0; 
      
    for i in range(n) :
        __gcd = gcd(__gcd, health[i]); 
  
    return __gcd; 
  
# Driver code 
if __name__ == "__main__" : 
  
    health = [ 5, 6, 1, 2, 3, 4 ]; 
    n = len(health); 
  
    print(minHealth(health, n)); 
  
# This code is contributed by AnkitRai01


C#
// C# implementation of the above approach
using System;
      
class GFG
{
  
// Function to return the minimum possible
// health of the last player
static int minHealth(int []health, int n)
{
  
    // Find the GCD of the array elements
    int gcd = 0;
    for (int i = 0; i < n; i++)
    {
        gcd = __gcd(gcd, health[i]);
    }
    return gcd;
}
  
static int __gcd(int a, int b) 
{ 
    return b == 0 ? a : __gcd(b, a % b);     
}
  
// Driver code
public static void Main(String []args) 
{
    int []health = { 5, 6, 1, 2, 3, 4 };
    int n = health.Length;
  
    Console.WriteLine(minHealth(health, n));
}
}
  
// This code is contributed by PrinciRaj1992


输出:
1