给定一个n个整数的排序数组A。任务是找到A的所有可能子序列的最小值之和。
注意:考虑到数字不会溢出。
例子:
Input: A = [ 1, 2, 4, 5]
Output: 17
Subsequences are [1], [2], [4], [5], [1, 2], [1, 4], [1, 5], [2, 4], [2, 5], [4, 5] [1, 2, 4], [1, 2, 5], [1, 4, 5], [2, 4, 5], [1, 2, 4, 5]
Minimums are 1, 2, 4, 5, 1, 1, 1, 2, 2, 4, 1, 1, 1, 2, 1.
Sum is 29
Input: A = [1, 2, 3]
Output: 11
方法:天真的方法是生成所有可能的子序列,找到它们的最小值并将它们相加得到结果。
高效的方法:假定对数组进行了排序,因此观察到最小元素出现2 n-1次,第二个最小元素出现2 n-2次,依此类推……让我们举个例子:
arr[] = {1, 2, 3}
Subsequences are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}
Minimum of each subsequence: {1}, {2}, {3}, {1}, {1}, {2}, {1}.
where
1 occurs 4 times i.e. 2 n-1 where n = 3.
2 occurs 2 times i.e. 2n-2 where n = 3.
3 occurs 1 times i.e. 2n-3 where n = 3.
因此,遍历数组并将当前元素即arr [i] * pow(2,n-1-i)添加到总和中。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find the sum
// of minimum of all subsequence
int findMinSum(int arr[], int n)
{
int occ = n - 1, sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i] * pow(2, occ);
occ--;
}
return sum;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findMinSum(arr, n);
return 0;
}
Java
// Java implementation of the above approach
class GfG
{
// Function to find the sum
// of minimum of all subsequence
static int findMinSum(int arr[], int n)
{
int occ = n - 1, sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i] * (int)Math.pow(2, occ);
occ--;
}
return sum;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 4, 5 };
int n = arr.length;
System.out.println(findMinSum(arr, n));
}
}
// This code is contributed by Prerna Saini
Python3
# Python3 implementation of the
# above approach
# Function to find the sum
# of minimum of all subsequence
def findMinSum(arr, n):
occ = n - 1
Sum = 0
for i in range(n):
Sum += arr[i] * pow(2, occ)
occ -= 1
return Sum
# Driver code
arr = [1, 2, 4, 5]
n = len(arr)
print(findMinSum(arr, n))
# This code is contributed
# by mohit kumar
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to find the sum
// of minimum of all subsequence
static int findMinSum(int []arr, int n)
{
int occ = n - 1, sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i] *(int) Math.Pow(2, occ);
occ--;
}
return sum;
}
// Driver code
public static void Main(String []args)
{
int []arr = { 1, 2, 4, 5 };
int n = arr.Length;
Console.WriteLine( findMinSum(arr, n));
}
}
// This code is contributed by Arnab Kundu
PHP
29
注意:要查找已排序数组中所有子序列的最大元素的总和,只需以相反的顺序遍历该数组并对Sum应用相同的公式即可。