Find the Array element left after alternate removal of minimum and maximum
Last Updated :
24 Mar, 2023
Given an array Arr of length N, it is reduced by 1 element at each step. Maximum and Minimum elements will be removed in alternating order from the remaining array until a single element is remaining in the array. The task is to find the remaining element in the given array.
Examples:
Input: arr[] = {1, 5, 4, 2}
Output: 2
Explanation:
Remove Max element i.e., 5 arr[] = {1, 4, 2}
Remove Min element i.e., 1 arr[] = {4, 2}
Remove Max element i.e., 4 arr[] = {2}
Input: arr[] = {5, 10}
Output: 5
Approach:
Follow the below idea to solve the problem:
The idea is to sort the array and return the middle element as all of the right and left elements will be removed in the process.
Follow the below steps to solve this problem:
- If N =1, return arr[0]
- Sort the array arr[]
- Return the middle element of the array i.e., arr[(N-1)/2]
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int lastRemaining( int arr[], int N)
{
if (N == 1)
return arr[0];
sort(arr, arr + N);
return arr[(N - 1) / 2];
}
int main()
{
int arr[] = { 1, 5, 4, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << lastRemaining(arr, N) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int lastRemaining( int arr[], int N)
{
if (N == 1 )
return arr[ 0 ];
Arrays.sort(arr);
return arr[(N - 1 ) / 2 ];
}
public static void main(String[] args)
{
int arr[] = { 1 , 5 , 4 , 2 };
int N = arr.length;
System.out.print(lastRemaining(arr, N));
}
}
|
Python3
def lastRemaining(arr, N):
if (N = = 1 ):
return arr[ 0 ]
arr.sort()
return arr[(N - 1 ) / / 2 ]
arr = [ 1 , 5 , 4 , 2 ]
N = len (arr)
print (lastRemaining(arr, N))
|
C#
using System;
class GFG {
static int lastRemaining( int [] arr, int N)
{
if (N == 1)
return arr[0];
Array.Sort(arr);
return arr[(N - 1) / 2];
}
public static void Main( string [] args)
{
int [] arr = { 1, 5, 4, 2 };
int N = arr.Length;
Console.Write(lastRemaining(arr, N));
}
}
|
Javascript
<script>
function lastRemaining(arr, N)
{
if (N == 1)
return arr[0];
let x = Math.floor((N - 1) / 2);
arr.sort( function (a, b) { return a - b })
return arr[x];
}
let arr = [1, 5, 4, 2];
let N = arr.length;
document.write(lastRemaining(arr, N));
</script>
|
Time Complexity: O(N * log(N)), for sorting the given array of size N.
Auxiliary Space: O(1), as constant extra space is required.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...