Fredo and Game

Fredo is playing a game. The rules of the game are:

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 Arr containing N elements corresponding to the N obstacles. If Fredo will hit obstacle i , then Arr[i]=1 else Arr[i]=0.
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 sumint nint a[])
{
    int flag = 0;
    int ans = 0;
    for (int i = 0i < ni++)
    {
        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";
    else
        cout << "No"
             << " " << ans << "\n";
}
int main()
{
    int sum = 5n = 5;

    int a[n] = {00101};

    fredoGame(sumna);

    return 0;
}


No comments:

Post a Comment