📌  相关文章
📜  执行给定操作后数组中剩余的最小元素

📅  最后修改于: 2021-10-26 05:21:26             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是从数组的两端删除元素,即在单个操作中,可以从数组的当前剩余元素中删除第一个或最后一个元素。这个操作需要以这样一种方式来执行,即剩下的最后一个元素将具有最小可能的值。打印这个最小值。
例子:

处理方法:这个问题可以贪心解决,从任一端取最大值的元素需要在一次操作中删除。遵循这种方法,直到数组中只剩下一个元素,最终将给我们原始数组中的最小元素。
下面是上述方法的实现:

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


Javascript


输出:
1

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程