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.


To solve this, we will follow these steps −

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


Let us see the following implementation to get better understanding −

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


{ 2, 1, 3 }