给定N个整数的数组arr [] ,任务是从数组的两端删除元素,即在一次操作中,可以从数组的当前剩余元素中删除第一个或最后一个元素。此操作需要以这样一种方式执行,即剩下的最后一个元素将具有最小的可能值。打印此最小值。
例子:
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
方法:可以贪婪地解决此问题,需要在单个操作中删除两端中最大值的元素。按照这种方法,直到数组中只剩下一个元素为止,最后我们将获得原始数组中的最小元素。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum possible
// value of the last element left after
// performing the given operations
int getMin(int arr[], int n)
{
int minVal = *min_element(arr, arr + n);
return minVal;
}
// Driver code
int main()
{
int arr[] = { 5, 3, 1, 6, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << getMin(arr, n);
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG
{
// Function to return the minimum possible
// value of the last element left after
// performing the given operations
static int getMin(int arr[], int n)
{
int minVal = Arrays.stream(arr).min().getAsInt();
return minVal;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 5, 3, 1, 6, 9 };
int n = arr.length;
System.out.println(getMin(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the minimum possible
# value of the last element left after
# performing the given operations
def getMin(arr, n) :
minVal = min(arr);
return minVal;
# Driver code
if __name__ == "__main__" :
arr = [ 5, 3, 1, 6, 9 ];
n = len(arr);
print(getMin(arr, n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the above approach
using System;
using System.Linq;
class GFG
{
// Function to return the minimum possible
// value of the last element left after
// performing the given operations
static int getMin(int []arr, int n)
{
int minVal = arr.Min();
return minVal;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 5, 3, 1, 6, 9 };
int n = arr.Length;
Console.WriteLine(getMin(arr, n));
}
}
// This code is contributed by Rajput-Ji
输出:
1