Minimum possible final health of the last monster in a game in C++


Problem statement

Given N monsters, each monster has initial health h[i] which is an integer. A monster is alive if its health is greater than 0.

In each turn a random monster kills another random monster, the monster which is attacked, its health reduces by the amount of health of the attacking monster. This process is continued until a single monster is left. What will be the minimum possible health of the last remained monster.

Example

If input array is {2, 14, 28, 56} then output will be 2 because When only the first monster keeps on attacking the remaining 3 monsters, the final health of the last monster will be 2, which is minimum.

Algorithm

We can obtain final answer using below GCD formula −

H(min) = gcd(h1, h2, …, hn)

Example

#include <iostream>
using namespace std;
int gcd(int a, int b) {
   if (a == 0)
   return b;
   return gcd(b % a, a);
}
int getPossibleHealth(int* health, int n) {
   int currentGcd = gcd(health[0], health[1]);
   for (int i = 2; i < n; ++i) {
      currentGcd = gcd(currentGcd, health[i]);
   }
   return currentGcd;
}
int main() {
   int health[] = { 4, 6, 8, 12 };
   int n = sizeof(health) / sizeof(health[0]);
   cout << "Possible final health = " << getPossibleHealth(health, n) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Possible final health = 2

Updated on: 22-Nov-2019

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements