给定数字N。任务是找到前N个自然数的置换P ,以使i%P i的总和最大。任务是找到最大可能的和而不是排列。
例子:
Input: N = 5
Output: 10
Possible permutation is 2 3 4 5 1.
Modulus values will be {1, 2, 3, 4, 0}.
1 + 2 + 3 + 4 + 0 = 10
Input: N = 8
Output: 28
方法:最大可能总和为(N *(N – 1))/ 2 ,它由排列2、3、4、5 ….. N,1形成。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the permutation of
// the first N natural numbers such that
// the sum of (i % Pi) is maximum possible
// and return the maximum sum
int Max_Sum(int n)
{
return (n * (n - 1)) / 2;
}
// Driver code
int main()
{
int n = 8;
// Function call
cout << Max_Sum(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to find the permutation of
// the first N natural numbers such that
// the sum of (i % Pi) is maximum possible
// and return the maximum sum
static int Max_Sum(int n)
{
return (n * (n - 1)) / 2;
}
// Driver code
public static void main (String[] args)
{
int n = 8;
// Function call
System.out.println(Max_Sum(n));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 implementation of the approach
# Function to find the permutation of
# the first N natural numbers such that
# the sum of (i % Pi) is maximum possible
# and return the maximum sum
def Max_Sum(n) :
return (n * (n - 1)) // 2;
# Driver code
if __name__ == "__main__" :
n = 8;
# Function call
print(Max_Sum(n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find the permutation of
// the first N natural numbers such that
// the sum of (i % Pi) is maximum possible
// and return the maximum sum
static int Max_Sum(int n)
{
return (n * (n - 1)) / 2;
}
// Driver code
public static void Main (String[] args)
{
int n = 8;
// Function call
Console.WriteLine(Max_Sum(n));
}
}
// This code is contributed by Princi Singh
Javascript
输出:
28