给定一个n个整数的排序数组A。任务是找到A的所有可能子数组的最小值之和。
例子:
Input: A = [ 1, 2, 4, 5]
Output: 23
Subsequences are [1], [2], [4], [5], [1, 2], [2, 4], [4, 5] [1, 2, 4], [2, 4, 5], [1, 2, 4, 5]
Minimums are 1, 2, 4, 5, 1, 2, 4, 1, 2, 1.
Sum is 23
Input: A = [1, 2, 3]
Output: 10
方法:天真的方法是生成所有可能的子数组,找到它们的最小值并将它们添加到结果中。
高效方法:假设对数组进行了排序,因此观察到最小元素出现N次,第二个最小元素出现N-1次,依此类推……让我们举个例子:
arr[] = {1, 2, 3}
Subarrays are {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}
Minimum of each subarray: {1}, {2}, {3}, {1}, {2}, {1}.
where
1 occurs 3 times i.e. n times where n = 3.
2 occurs 2 times i.e. n-1 times where n = 3.
3 occurs 1 times i.e. n-2 times where n = 3.
因此,遍历数组并将当前元素即(arr [i] * ni)添加到总和中。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find the sum
// of minimum of all subarrays
int findMinSum(int arr[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i] * (n - i);
return sum;
}
// Driver code
int main()
{
int arr[] = { 3, 5, 7, 8 };
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 subarrays
static int findMinSum(int arr[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i] * (n - i);
return sum;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 5, 7, 8 };
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 subarrays
def findMinSum(arr, n):
sum = 0
for i in range(0, n):
sum += arr[i] * (n - i)
return sum
# Driver code
arr = [3, 5, 7, 8 ]
n = len(arr)
print(findMinSum(arr, n))
# This code has been contributed
# by 29AjayKumar
C#
// C# implementation of the above approach
using System;
class GfG
{
// Function to find the sum
// of minimum of all subarrays
static int findMinSum(int []arr, int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i] * (n - i);
return sum;
}
// Driver code
public static void Main(String []args)
{
int []arr = { 3, 5, 7, 8 };
int n = arr.Length;
Console.WriteLine(findMinSum(arr, n));
}
}
// This code is contributed by Arnab Kundu
PHP
49
注意:要查找已排序数组中所有子数组的最大元素的总和,只需以相反的顺序遍历该数组,并对总和应用相同的公式。