📌  相关文章
📜  最大化 arr[i]*i 的总和

📅  最后修改于: 2021-10-26 05:37:18             🧑  作者: Mango

给定一个包含N 个整数的数组。您可以重新排列数组的元素。任务是找到 Σarr[i]*i 的最大值,其中 i = 0, 1, 2,…., n – 1。

例子:

Input : N = 4, arr[] = { 3, 5, 6, 1 }
Output : 31
If we arrange arr[] as { 1, 3, 5, 6 }. 
Sum of arr[i]*i is 1*0 + 3*1 + 5*2 + 6*3 
= 31, which is maximum

Input : N = 2, arr[] = { 19, 20 }
Output : 20

一个简单的解决方案是生成给定数组的所有排列。对于每个排列,计算 Σarr[i]*i 的值并最终返回最大值。
一个有效的解决方案是基于这样一个事实:最大值应该被缩放到最大值,而最小值应该被缩放到最小。所以我们将 i 的最小值乘以 arr[i] 的最小值。因此,按递增顺序对给定数组进行排序并计算 arr[i]*i 的总和,其中 i = 0 到 n-1。
下面是这个方法的实现:

C++
// CPP program to find the maximum value
// of i*arr[i]
#include
using namespace std;
 
int maxSum(int arr[], int n)
{ 
  // Sort the array
  sort(arr, arr + n);
 
  // Finding the sum of arr[i]*i
  int sum = 0;
  for (int i = 0; i < n; i++)
    sum += (arr[i]*i);
 
  return sum;
}
 
// Driven Program
int main()
{
  int arr[] = { 3, 5, 6, 1 };
  int n = sizeof(arr)/sizeof(arr[0]);
 
  cout << maxSum(arr, n) << endl;
  return 0;
}


Java
// Java program to find the
// maximum value of i*arr[i]
import java.util.*;
 
class GFG {
 
    static int maxSum(int arr[], int n)
    {   
    // Sort the array
    Arrays.sort(arr);
 
    // Finding the sum of arr[i]*i
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += (arr[i] * i);
 
    return sum;
    }
 
    // Driven Program
    public static void main(String[] args)
    {
    int arr[] = { 3, 5, 6, 1 };
    int n = arr.length;
 
    System.out.println(maxSum(arr, n));
 
    }
}
// This code is contributed by Prerna Saini


Python3
# Python program to find the
# maximum value of i*arr[i]
def maxSum(arr,n):
 
    #  Sort the array
    arr.sort()
 
    # Finding the sum of
    # arr[i]*i
    sum = 0
    for i in range(n):
        sum += arr[i] * i
         
    return sum
 
# Driver Program
arr = [3,5,6,1]
n = len(arr)
print(maxSum(arr,n))
 
# This code is contributed
# by Shrikant13


C#
// C# program to find the
// maximum value of i*arr[i]
using System;
 
class GFG {
     
    // Function to find the
    // maximum value of i*arr[i]
    static int maxSum(int[] arr, int n)
    {
         
        // Sort the array
        Array.Sort(arr);
     
        // Finding the sum of arr[i]*i
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += (arr[i] * i);
     
        return sum;
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = {3, 5, 6, 1};
        int n = arr.Length;
     
        Console.WriteLine(maxSum(arr, n));
 
    }
}
 
// This code is contributed by Ajit.


PHP


Javascript


输出:

31

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程