Fun Game


 A and BB are playing a game. In this game, both of them are initially provided with a list of n numbers. (Both have the same list but their own copy).

Now, they both have a different strategy to play the game. A picks the element from the start of his list. B picks from the end of his list.

You need to generate the result in form of an output list.

Method to be followed at each step to build the output list is:

  1. If the number picked by A is bigger than B then this step's output is 1 . B removes the number that was picked from their list.
  2. If the number picked by A is smaller than B then this step's output is 2 . A removes the number that was picked from their list.
  3. If both have the same number then this step's output is 0 . Both A and B  remove the number that was picked from their list.

This game ends when at least one of them has no more elements to be picked i.e. when the list gets empty.

Example:

Input:  n =3, arr={1,2,3}
Output: 2 2 0

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<intfunGame(int nvector<int&arr)
{
    stack<intst;
    queue<intq;

    vector<intres;
    for (int i = 0i < ni++)
    {
        st.push(arr[i]);
        q.push(arr[i]);
    }
    while (!st.empty() && !q.empty())
    {
        int b = st.top();
        int a = q.front();
        if (a > b)
        {
            res.push_back(1);
            st.pop();
        }
        else if (a < b)
        {
            res.push_back(2);
            q.pop();
        }
        else
        {
            res.push_back(0);
            st.pop();
            q.pop();
        }
    }
    return res;
}
int main()
{

    int n = 3;

    vector<intarr = {123};

    vector<intres = funGame(narr);
    for (int i = 0i < res.size(); i++)
        cout << res[i] << " ";

    return 0;
}


No comments:

Post a Comment