A and B are playing a game. In this game, both of them are initially provided with a list of numbers. (Both have the same list but their own copy).
Now, they both have a different strategy to play the game. picks the element from the start of his list. 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:
- If the number picked by is bigger than then this step's output is . removes the number that was picked from their list.
- If the number picked by is smaller than then this step's output is . removes the number that was picked from their list.
- If both have the same number then this step's output is . Both and 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<int> funGame(int n, vector<int> &arr){stack<int> st;queue<int> q;vector<int> res;for (int i = 0; i < n; i++){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<int> arr = {1, 2, 3};vector<int> res = funGame(n, arr);for (int i = 0; i < res.size(); i++)cout << res[i] << " ";return 0;}
No comments:
Post a Comment