C++ code to find final number after min max removal game

Suppose we have an array A with n elements. There are n numbers written on a board. Amal and Bimal are playing a turn based game. In each turn, they select a number and remove it from board. Amal plays first. Amal wants to minimize the last number that he would left on the board, and Bimal wants to maximize it. We have to find the number which will remain on the board.

So, if the input is like A = [2, 1, 3], then the output will be 2, because Amal will remove 3, Bimal will remove 1, so the final number will be 2.

Steps

To solve this, we will follow these steps −

n := size of A
sort the array A
return A[floor of ((n - 1)/2)]

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;
int solve(vector A){
   int n = A.size();
   sort(A.begin(), A.end());
   return A[(n - 1) / 2];
}
int main(){
   vector A = { 2, 1, 3 };
   cout 

Input

{ 2, 1, 3 }

Output

2
Updated on: 2022-03-15T05:36:51+05:30

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements