📌  相关文章
📜  用总和 K 最大化 Array 中相邻元素之间的绝对差的总和

📅  最后修改于: 2022-05-13 01:56:05.963000             🧑  作者: Mango

用总和 K 最大化 Array 中相邻元素之间的绝对差的总和

给定两个整数 N 和 K ,任务是最大化长度为N和总和K的数组的相邻元素之间的绝对差之和。
例子:

方法:
要最大化相邻元素的总和,请执行以下步骤:

  • 如果N为 2,则通过将K放在 1 索引中并将0放在另一个索引中,可能的最大总和为K。
  • 如果N为 1,则可能的最大总和将始终为 0。
  • 对于N的所有其他值,答案将是2 * K

下面是上述方法的实现:

C++
// C++ program to maximize the
// sum of absolute differences
// between adjacent elements
#include 
using namespace std;
  
// Function for maximizing the sum
int maxAdjacentDifference(int N, int K)
{
    // Difference is 0 when only
    // one element is present
    // in array
    if (N == 1) {
        return 0;
    }
  
    // Difference is K when
    // two elements are
    // present in array
    if (N == 2) {
        return K;
    }
  
    // Otherwise
    return 2 * K;
}
  
// Driver code
int main()
{
  
    int N = 6;
    int K = 11;
  
    cout << maxAdjacentDifference(N, K);
  
    return 0;
}


Java
// Java program to maximize the
// sum of absolute differences
// between adjacent elements
import java.util.*;
  
class GFG{
  
// Function for maximising the sum
static int maxAdjacentDifference(int N, int K)
{
      
    // Difference is 0 when only
    // one element is present
    // in array
    if (N == 1)
    {
        return 0;
    }
  
    // Difference is K when
    // two elements are
    // present in array
    if (N == 2) 
    {
        return K;
    }
  
    // Otherwise
    return 2 * K;
}
  
// Driver code
public static void main(String[] args)
{
    int N = 6;
    int K = 11;
  
    System.out.print(maxAdjacentDifference(N, K));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program to maximize the
# sum of absolute differences
# between adjacent elements
  
# Function for maximising the sum
def maxAdjacentDifference(N, K):
  
    # Difference is 0 when only
    # one element is present
    # in array
    if (N == 1):
        return 0;
      
    # Difference is K when
    # two elements are
    # present in array
    if (N == 2):
        return K;
      
    # Otherwise
    return 2 * K;
  
# Driver code
N = 6;
K = 11;
print(maxAdjacentDifference(N, K));
  
# This code is contributed by Code_Mech


C#
// C# program to maximize the
// sum of absolute differences
// between adjacent elements
using System;
  
class GFG{
  
// Function for maximising the sum
static int maxAdjacentDifference(int N, int K)
{
      
    // Difference is 0 when only
    // one element is present
    // in array
    if (N == 1)
    {
        return 0;
    }
  
    // Difference is K when
    // two elements are
    // present in array
    if (N == 2) 
    {
        return K;
    }
  
    // Otherwise
    return 2 * K;
}
  
// Driver code
public static void Main(String[] args)
{
    int N = 6;
    int K = 11;
  
    Console.Write(maxAdjacentDifference(N, K));
}
}
  
// This code is contributed by 29AjayKumar


Javascript


输出:
22

时间复杂度: O(1)