给定一个由n个整数组成的数组,我们可以通过以下操作删除该数组的一个元素。
操作:我们选择数组中的任意两个数字并删除较大的数字,此操作中包含的成本等于较小的数字。
您必须通过以最小的成本执行上述操作,将数组简化为单个元素。
例子:
Input : arr[] = {3 4}
Output : 3
We remove 4 by picking both elements and paying cost equal to smaller.
Input : 4 2 5
Output : 4
We first pick 4, 2, remove 4 by paying cost 2. Then we remove 5 by again paying cost 2.
由于我们必须将数组简化为单个元素,因此可以假定,如果我们选择任意两个数字,则删除较大数字的成本等于较小数字。因此,为了使总成本最小化,我们总是将最小的数字与其他数字一起删除以消除总成本,因此总成本将为(n-1)*最小的数字。
C++
// C++ Program for the above approach
#include
using namespace std;
// this function returns the minimum
// cost of the array
int getMinCost(int arr[], int n)
{
int min_ele = *min_element(arr, arr+n);
return min_ele * (n - 1);
}
int main()
{
int arr[] = { 4, 2, 5 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << getMinCost(arr, n) << endl;
return 0;
}
Java
// Java Program for the above approach
import java.util.Collections;
import java.util.Arrays;
public class GfG {
// This function returns the minimum
// cost of the array
public static int getMinCost(Integer arr[], int n)
{
int min_ele = Collections.min(Arrays.asList(arr));
return min_ele * (n - 1);
}
// Driver code
public static void main(String []args){
Integer[] arr = { 4, 2, 5 };
int n = arr.length;
System.out.println(getMinCost(arr, n));
}
}
// This code is contributed by Rituraj Jain
Python3
# Python3 Program for the above approach
# Function returns the minimum
# cost of the array
def getMinCost(arr, n):
min_ele = min(arr)
return min_ele * (n - 1)
# Driver Code
arr = [4, 2, 5]
n = len(arr)
print(getMinCost(arr, n))
# This code is contributed
# by Shrikant13
C#
// C# Program for the above approach
using System;
using System.Linq;
class GfG
{
// This function returns the minimum
// cost of the array
public static int getMinCost(int []arr, int n)
{
int min_ele = arr.Min();
return min_ele * (n - 1);
}
// Driver code
public static void Main(String []args)
{
int[] arr = { 4, 2, 5 };
int n = arr.Length;
Console.WriteLine(getMinCost(arr, n));
}
}
// This code contributed by Rajput-Ji
PHP
输出:
4