Find the minimum possible health of the winning player
Last Updated :
10 Jul, 2022
Given an array health[] where health[i] is the health of the ith player in a game, any player can attack any other player in the game. The health of the player being attacked will be reduced by the amount of health the attacking player has. The task is to find the minimum possible health of the winning player.
Examples:
Input: health[] = {4, 6, 8}
Output: 2
4 attacks 6, health[] = {4, 2, 8}
2 attacks 4 twice, health[] = {0, 2, 8}
2 attacks 8 four times, health[] = {0, 2, 0}
Input: health[] = {4, 1, 5, 3}
Output: 1
Approach: In order to minimize the health of the last player, only the player with the smaller health will attack a player with the larger health and by doing so if only two players are involved then the minimum health of the last player is nothing but the GCD of the initial healths of the two players. So, the result will be the GCD of all the elements of the given array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minHealth( int health[], int n)
{
int gcd = 0;
for ( int i = 0; i < n; i++) {
gcd = __gcd(gcd, health[i]);
}
return gcd;
}
int main()
{
int health[] = { 5, 6, 1, 2, 3, 4 };
int n = sizeof (health) / sizeof ( int );
cout << minHealth(health, n);
return 0;
}
|
Java
class GFG
{
static int minHealth( int health[], int n)
{
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);
}
public static void main(String []args)
{
int health[] = { 5 , 6 , 1 , 2 , 3 , 4 };
int n = health.length;
System.out.println(minHealth(health, n));
}
}
|
Python3
from math import gcd
def minHealth(health, n) :
__gcd = 0 ;
for i in range (n) :
__gcd = gcd(__gcd, health[i]);
return __gcd;
if __name__ = = "__main__" :
health = [ 5 , 6 , 1 , 2 , 3 , 4 ];
n = len (health);
print (minHealth(health, n));
|
C#
using System;
class GFG
{
static int minHealth( int []health, int n)
{
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);
}
public static void Main(String []args)
{
int []health = { 5, 6, 1, 2, 3, 4 };
int n = health.Length;
Console.WriteLine(minHealth(health, n));
}
}
|
Javascript
<script>
function minHealth(health, n)
{
var gcd = 0;
for ( var i = 0; i < n; i++)
{
gcd = __gcd(gcd, health[i]);
}
return gcd;
}
function __gcd(a, b)
{
return b == 0 ? a : __gcd(b, a % b);
}
var health = [ 5, 6, 1, 2, 3, 4 ];
var n = health.length;
document.write(minHealth(health, n));
</script>
|
Time Complexity : O(log(a+b)) ,where a and b are elements of health array.
Space Complexity : O(1) ,as we are not using any extra space.
Share your thoughts in the comments
Please Login to comment...