给定两个整数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 maximising 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) 。
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。