Andy wants to play a game with his little brother, Bob. The game starts with an array of distinct integers and the rules are as follows:
- Bob always plays first.
- In a single move, a player chooses the maximum element in the array. He removes it and all elements to its right. For example, if the starting array , then it becomes after removing .
- The two players alternate turns.
- The last player who can make a move wins.
Andy and Bob play g games. Given the initial array for each game, find and print the name of the winner on a new line. If Andy wins, print ANDY
; if Bob wins, print BOB
.
To continue the example above, in the next move Andy will remove . Bob will then remove and win because there are no more integers to remove.
Example:
Input: n = 5, arr = {5, 2, 6, 3, 4}
Output: ANDY
Approach
Java
public class GamingArray {public static void main(String[] args) {int n = 5;int[] arr = { 5, 2, 6, 3, 4 };System.out.println(gamingArray(arr));}static String gamingArray(int[] arr) {int count = 0;int maxValue = 0;for (int i = 0; i < arr.length; i++) {if (arr[i] > maxValue) {maxValue = arr[i];count++;}}if (count % 2 == 0)return "ANDY";return "BOB";}}
C++
#include <bits/stdc++.h>using namespace std;string gamingArray(vector<int> arr){int count = 0;int maxValue = 0;for (int i = 0; i < arr.size(); i++){if (arr[i] > maxValue){maxValue = arr[i];count++;}}if (count % 2 == 0)return "ANDY";return "BOB";}int main(){int n = 5;vector<int> arr = {5, 2, 6, 3, 4};cout << gamingArray(arr) << "\n";return 0;}
No comments:
Post a Comment