📌  相关文章
📜  重新排列数组以最大化i * arr [i]

📅  最后修改于: 2021-05-06 19:23:17             🧑  作者: Mango

给定一个由N个整数组成的数组,您必须以任何顺序选择所有这些整数。对于您选择的每个整数,您将获得等于以下值的点:选定整数*当前整数之前选定的整数数量。您的任务是最大化这些点。
注意:您可以选择每个整数正好1次。

例子:

这个想法是使用贪婪方法,即最大化最大元素的乘数。
我们对给定的数组进行排序,并从第一个元素开始以这种排序的方式选择元素。

下面是上述方法的实现:

C++
// C++ program for the Optimal Solution
#include  
#include 
using namespace std;
  
    // Function to calculate the maximum points
    // earned by making an optimal selection on
    // the given array
    static int findOptimalSolution(int a[], int N)
    {
        // Sorting the array
        sort(a, a+N); 
        // Variable to store the total points earned
        int points = 0;
  
        for (int i = 0; i < N; i++) {
            points += a[i] * i;
        }
        return points;
    }
  
    // Driver code
int main() {
    int a[] = { 1, 4, 2, 3, 9 };
    int N = sizeof(a)/sizeof(a[0]);
        cout<<(findOptimalSolution(a, N));
      
    return 0;
}


Java
// Java program for the Optimal Solution
import java.io.*;
import java.util.*;
  
class GFG {
  
    // Function to calculate the maximum points
    // earned by making an optimal selection on
    // the given array
    static int findOptimalSolution(int[] a, int N)
    {
        // Sorting the array
        Arrays.sort(a);
  
        // Variable to store the total points earned
        int points = 0;
  
        for (int i = 0; i < N; i++) {
            points += a[i] * i;
        }
        return points;
    }
  
    // Driver code
    public static void main(String args[])
    {
        int[] a = { 1, 4, 2, 3, 9 };
        int N = a.length;
        System.out.println(findOptimalSolution(a, N));
    }
}


Python3
# Python3 program for the Optimal Solution 
  
# Function to calculate the maximum points 
# earned by making an optimal selection on 
# the given array 
def findOptimalSolution(a, N) :
          
    # Sorting the array 
    a.sort()  
      
    # Variable to store the total points earned 
    points = 0 
    
    for i in range(0, N):
        points += a[i] * i 
       
    return points 
    
      
if __name__ == "__main__":
      
    a = [1, 4, 2, 3, 9] 
    N = len(a) 
    print(findOptimalSolution(a, N))


C#
//C# program for the Optimal Solution
using System;
  
public class GFG{
      
        // Function to calculate the maximum points 
    // earned by making an optimal selection on 
    // the given array 
    static int findOptimalSolution(int[]a, int N) 
    { 
        // Sorting the array 
        Array.Sort(a); 
  
        // Variable to store the total points earned 
        int points = 0; 
  
        for (int i = 0; i < N; i++) { 
            points += a[i] * i; 
        } 
        return points; 
    } 
  
    // Driver code 
    static public void Main (){
        int[] a = { 1, 4, 2, 3, 9 }; 
        int N = a.Length; 
        Console.WriteLine(findOptimalSolution(a, N)); 
    }
//This code is contributed by ajit    
}


PHP


输出:
56