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

📅  最后修改于: 2021-10-26 06:42:33             🧑  作者: 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


Javascript


输出:
56

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