Minimum element left from the array after performing given operations
Last Updated :
29 May, 2022
Given an array arr[] of N integers, the task is to remove the elements from both the ends of the array i.e. in a single operation, either the first or the last element can be removed from the current remaining elements of the array. This operation needs to be performed in such a way that the last element left will have the minimum possible value. Print this minimum value.
Examples:
Input: arr[] = {5, 3, 1, 6, 9}
Output: 1
Operation 1: arr[] = {5, 3, 1, 6}
Operation 2: arr[] = {5, 3, 1}
Operation 3: arr[] = {3, 1}
Operation 4: arr[] = {1}
Input: arr[] = {2, 6, 4, 8, 2, 6}
Output: 2
Approach: This problem can be solved greedily, the element with the maximum value from either of the end needs to be removed in a single operation. Following this approach until only one element is left in the array will give us the minimum element from the original array in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMin( int arr[], int n)
{
int minVal = *min_element(arr, arr + n);
return minVal;
}
int main()
{
int arr[] = { 5, 3, 1, 6, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << getMin(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int getMin( int arr[], int n)
{
int minVal = Arrays.stream(arr).min().getAsInt();
return minVal;
}
public static void main(String[] args)
{
int arr[] = { 5 , 3 , 1 , 6 , 9 };
int n = arr.length;
System.out.println(getMin(arr, n));
}
}
|
Python3
def getMin(arr, n) :
minVal = min (arr);
return minVal;
if __name__ = = "__main__" :
arr = [ 5 , 3 , 1 , 6 , 9 ];
n = len (arr);
print (getMin(arr, n));
|
C#
using System;
using System.Linq;
class GFG
{
static int getMin( int []arr, int n)
{
int minVal = arr.Min();
return minVal;
}
public static void Main(String[] args)
{
int []arr = { 5, 3, 1, 6, 9 };
int n = arr.Length;
Console.WriteLine(getMin(arr, n));
}
}
|
Javascript
<script>
function getMin(arr, n)
{
var minVal = Math.min.apply(Math, arr);
return minVal;
}
var arr = [ 5, 3, 1, 6, 9 ];
var n = arr.length;
document.write(getMin(arr, n));
</script>
|
Time Complexity: O(N), as we are using inbuilt min_element function which will cost us O(N) time.
Auxiliary Space: O(1), as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...