📜  通过从数组中选择对的最小值来求和

📅  最后修改于: 2021-04-28 13:51:25             🧑  作者: Mango

给定n个元素的数组A []。我们需要选择两个相邻的元素并删除它们中较大的元素,并将其中较小的元素存储到另一个数组B []中。我们需要执行此操作,直到数组A []仅包含单个元素。最后,我们必须以使其元素的总和最小的方式构造数组B []。打印数组B []的总和。
例子:

Input : A[] = {3, 4} 
Output : 3

Input : A[] = {2, 4, 1, 3}
Output : 3

解决这个问题有一个简单的技巧,那就是始终选择数组A []及其相邻元素中的最小元素,删除相邻元素并将最小元素复制到数组B []中。同样,对于下一次迭代,我们具有相同的最小元素以及将要删除的任何随机相邻元素。经过n-1次运算后,A []的所有元素都被删除,除了最小的一个元素外,同时数组B []包含“ n-1”个元素,并且所有元素均等于数组A []的最小元素。
因此,数组B []的总和等于最小*(n-1)

C++
// CPP program to minimize the cost
// of array minimization
#include 
using namespace std;
 
// Returns minimum possible sum in
// array B[]
int minSum(int A[], int n)
{
    int min_val = *min_element(A, A+n);
    return (min_val * (n-1));
}
 
// driver function
int main()
{
    int A[] = { 3, 6, 2, 8, 7, 5};
    int n = sizeof(A)/ sizeof (A[0]);
    cout << minSum(A, n);
    return 0;
}


Java
// Java program to minimize the
// cost of array minimization
import java.util.Arrays;
 
public class GFG {
 
// Returns minimum possible
// sum in array B[]
    static int minSum(int[] A, int n) {
        int min_val = Arrays.stream(A).min().getAsInt();
        return (min_val * (n - 1));
    }
 
    // Driver Code
    static public void main(String[] args) {
        int[] A = {3, 6, 2, 8, 7, 5};
        int n = A.length;
        System.out.println((minSum(A, n)));
 
    }
}
// This code is contributed by Rajput-Ji


Python
# Python code for minimum cost of
# array minimization
 
# Function defintion for minCost
def minSum(A):
 
    # find the minimum element of A[]
    min_val = min(A);
 
    # return the answer
    return min_val * (len(A)-1)
 
# driver code
A = [7, 2, 3, 4, 5, 6]
print (minSum(A))


C#
// C# program to minimize the
// cost of array minimization
using System;
using System.Linq;
 
public class GFG
{
 
// Returns minimum possible
// sum in array B[]
static int minSum(int []A, int n)
{
    int min_val = A.Min();
    return (min_val * (n - 1));
}
     
    // Driver Code
    static public void Main()
    {
        int []A = {3, 6, 2, 8, 7, 5};
        int n = A.Length;
        Console.WriteLine(minSum(A, n));
         
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

10