📌  相关文章
📜  相邻元素之差的最大和

📅  最后修改于: 2021-04-24 15:42:37             🧑  作者: Mango

给定数字n。我们必须找到n的所有排列的最大和。最大和为数组中相邻元素的绝对差之和。

例子:

Input : 3
Output : 3
Permutations of size 3 are:
{1, 2, 3} = 1 + 1
{1, 3, 2} = 2 + 1
{2, 1, 3} = 1 + 2
{2, 3, 1} = 1 + 2
{3, 1, 2} = 2 + 1
{3, 2, 1} = 1 + 1

Input : 2
Output : 1
Permutations of 2 are:
{1, 2} = 1
{2, 1} = 1 

让我们以n = 5为例。我们可以很容易地看到我们可以放置1 5 2 4 3这样的数字。
abs(1-5)= 4
abs(5-2)= 3
abs(2-4)= 2
abs(4-3)= 1
总和为4 + 3 + 2 + 1 = 10。
通常,此排列的总和为n(n-1)/ 2。
但是,如果我们在此排列开始时移动3,则会获得最大和
即3 1 5 2 4。
总和将变为2 + 4 + 3 + 2 = 11。

最终关系= n(n – 1)/ 2 – 1 + n / 2,其中n> 1。

具有最大和的n的排列将为n / 2,n-1、2,n-2、3,n-3。
因此,我们必须找到此置换的总和,即为n(n-1)/ 2 – 1 + n / 2。
下面是上述方法的实现。

C++
// CPP program to find maximum sum of
// adjacent elements of permutation of n
#include 
using namespace std;
  
// To find max sum of permutation
int maxSum(int n)
{
    // Base case
    if (n == 1)
        return 1;
  
    // Otherwise max sum will
    // be (n*(n-1)/2) - 1 + n/2
    else
        return (n * (n - 1) / 2) - 1 + n / 2;
}
  
// Driver program to test maxSum()
int main()
{
    int n = 3;
    cout << maxSum(n);
    return 0;
}


Java
// Java program to find maximum sum of
// adjacent elements of permutaion of n
public class Main {
  
    // To find max sum of permutation
    static int maxSum(int n)
    {
        // Base case
        if (n == 1)
            return 1;
  
        // Otherwise max sum will
        // be (n*(n-1)/2) - 1 + n/2
        else
            return (n * (n - 1) / 2) - 1 + n / 2;
    }
  
    // Driver program to test maxSum()
    public static void main(String[] args)
    {
        int n = 3;
        System.out.println(maxSum(n));
    }
}


Python 3
# Python program to find maximum sum of
# adjacent elements of permutation of n
  
# To find max sum of permutation
def maxSum(n):
  
    # Base case
    if (n == 1):
        return 1
   
    # Otherwise max sum will
    # be (n*(n-1)/2) - 1 + n / 2
    else:
        return int((n * (n - 1) / 2) - 1 + n / 2)
   
# Driver program to test maxSum()
n = 3
print(maxSum(n))
  
# This code is contributed
# by Azkia Anam.


C#
// C# program to find maximum sum of
// adjacent elements of permutaion of n
using System;
  
public class main {
  
    // To find max sum of permutation
    static int maxSum(int n)
    {
          
        // Base case
        if (n == 1)
            return 1;
  
        // Otherwise max sum will
        // be (n*(n-1)/2) - 1 + n/2
        else
            return (n * (n - 1) / 2) 
                           - 1 + n / 2;
    }
  
    // Driver program to test maxSum()
    public static void Main()
    {
        int n = 3;
          
        Console.WriteLine(maxSum(n));
    }
}
  
// This code is contributed by vt_m.


PHP


输出:

3