Initially, you are given A units of ammo. There are N obstacles placed on a path. When you hit an obstacle, you gain three units of ammo and lose one unit of ammo. When you don't hit an obstacle, you lose one unit of ammo. If at any instance, you are left with 0 ammo units, the game ends there.
Fredo has an array containing N elements corresponding to the N obstacles. If Fredo will hit obstacle i , then else .
Fredo asks you to tell him if he will be able to reach the end of the path. If yes, then also tell him the remaining number of ammo units.
If he is not able to reach the end of the path, tell him the obstacle index at which his game would end.
Note: If Fredo reaches the last obstacle, he is said to reach the end of the path.
Example:
Input: sum = 5, n = 5, a = {0, 0, 1, 0, 1}
Output: Yes 6
Approach
C++
#include <bits/stdc++.h>using namespace std;void fredoGame(int sum, int n, int a[]){int flag = 0;int ans = 0;for (int i = 0; i < n; i++){if (a[i] == 0){sum -= 1;}else{sum += 2;}if (sum == 0 && i < n - 1){flag = 1;ans = i + 1;break;}}if (flag == 0)cout << "Yes"<< " " << sum << "\n";elsecout << "No"<< " " << ans << "\n";}int main(){int sum = 5, n = 5;int a[n] = {0, 0, 1, 0, 1};fredoGame(sum, n, a);return 0;}
No comments:
Post a Comment