用总和 K 最大化 Array 中相邻元素之间的绝对差的总和
给定两个整数 N 和 K ,任务是最大化长度为N和总和K的数组的相邻元素之间的绝对差之和。
例子:
Input: N = 5, K = 10
Output: 20
Explanation:
The array arr[] with sum 10 can be {0, 5, 0, 5, 0}, maximizing the sum of absolute difference of adjacent elements ( 5 + 5 + 5 + 5 = 20)
Input: N = 2, K = 10
Output: 10
方法:
要最大化相邻元素的总和,请执行以下步骤:
- 如果N为 2,则通过将K放在 1 索引中并将0放在另一个索引中,可能的最大总和为K。
- 如果N为 1,则可能的最大总和将始终为 0。
- 对于N的所有其他值,答案将是2 * K 。
Illustration:
For N = 3, the arrangement {0, K, 0} maximizes the sum of absolute difference between adjacent elements to 2 * K.
For N = 4, the arrangement {0, K/2, 0, K/2} or {0, K, 0, 0} maximizes the required sum of absolute difference between adjacent elements to 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) 。