📌  相关文章
📜  排序数组的所有子数组的最小元素的总和

📅  最后修改于: 2021-04-23 06:42:09             🧑  作者: Mango

给定一个n个整数的排序数组A。任务是找到A的所有可能子数组的最小值之和。

例子:

方法:天真的方法是生成所有可能的子数组,找到它们的最小值并将它们添加到结果中。

高效方法:假设对数组进行了排序,因此观察到最小元素出现N次,第二个最小元素出现N-1次,依此类推……让我们举个例子:

因此,遍历数组并将当前元素即(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

注意:要查找已排序数组中所有子数组的最大元素总和,只需以相反的顺序遍历该数组,并对总和应用相同的公式。