给定一个包含 N 个整数的数组,您必须按任意顺序选择所有这些整数。对于您选择的每个整数,您将获得等于以下值的分数:所选整数 * 在当前整数之前选择的整数数。你的任务是最大化这些点。
注意:您可以精确地选择每个整数 1 次。
例子:
Input: a = {1, 4, 2, 3, 9}
Output: 56
The optimal solution for this array would be select the numbers in the order 1, 2, 3, 4, 9 that gives points 0, 2, 6, 12, 36 respectively and giving a total maximum points of 56.
Input: a = {1, 2, 2, 4, 9}
Output: 54
The optimal solution for this array would be select the numbers in the order 1, 2, 2, 4, 9 that gives points 0, 2, 4, 12, 36 respectively and giving a total maximum points of 54.
这个想法是使用贪婪方法,即最大化最大元素的乘数。
我们对给定的数组进行排序并以这种排序方式开始挑选元素,从第一个元素开始。
下面是上述方法的实现:
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 现场工作专业课程和学生竞争性编程现场课程。