
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Code to Find Minimum Moves with Weapons to Kill Enemy
Suppose we have an array A with n elements, and another number H. H is health of an enemy. We have n weapons and damaging power of ith weapon is A[i]. Different weapons can be used to kill the enemy. We cannot use same weapon twice in a row. We have to count minimum how many times we can use weapons to kill the enemy.
So, if the input is like A = [2, 1, 7]; H = 11, then the output will be 3, because if we use weapon with damage power 7, then use 2 then again use 7 we can kill the enemy.
Steps
To solve this, we will follow these steps −
sort the array A n := size of A x := (A[n - 1] + A[n - 2]) return H / x * 2 + (H mod x + A[n - 1] - 1) / A[n-1]
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A, int H){ sort(A.begin(), A.end()); int n = A.size(); int x = (A[n - 1] + A[n - 2]); return H / x * 2 + (H % x + A[n - 1] - 1) / A[n - 1]; } int main(){ vector<int> A = { 2, 1, 7 }; int H = 11; cout << solve(A, H) << endl; }
Input
{ 2, 1, 7 }, 11
Output
3
Advertisements