给定两个整数N和K ,任务是找到一个长度为N的整数序列,以使序列中所有元素的总和为K,并且所有连续元素之间的绝对差之和最小。打印此最小化的总和。
例子:
Input: N = 3, K = 56
Output: 1
The sequence is {19, 19, 18} and the sum of absolute
differences of all the consecutive elements is
|19 – 19| + |19 – 18| = 0 + 1 = 1 which is the minimum possible.
Input: N = 12, K = 48
Output: 0
The sequence is {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}.
方法:可能有两种情况:
- 当K%N = 0时,答案将为0,因为K可以平均分为N个部分,即序列中的每个元素都将相等。
- 当K%N!= 0时,答案将为1,因为可以按以下方式排列序列:
- (K –(K%N))可被N整除,因此可以在所有N个部分中平均分配。
- 剩下的(K%N)值可以以最小化连续绝对差的方式进行划分,即在第一个或最后一个(K%N)元素上加1 ,并且序列的类型为{x,x, x,x,y,y,y,y}得出的最小和为1 。
下面是上述方法的实现:
CPP
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimized sum
int minimum_sum(int n, int k)
{
// If k is divisible by n
// then the answer will be 0
if (k % n == 0)
return 0;
// Else the answer will be 1
return 1;
}
// Driver code
int main()
{
int n = 3, k = 56;
cout << minimum_sum(n, k);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Function to return the minimized sum
static int minimum_sum(int n, int k)
{
// If k is divisible by n
// then the answer will be 0
if (k % n == 0)
return 0;
// Else the answer will be 1
return 1;
}
// Driver code
public static void main (String[] args)
{
int n = 3, k = 56;
System.out.println (minimum_sum(n, k));
}
}
// This code is contributed By @ajit_23
Python3
# Python3 implementation of the approach
# Function to return the minimized sum
def minimum_sum(n, k):
# If k is divisible by n
# then the answer will be 0
if (k % n == 0):
return 0;
# Else the answer will be 1
return 1
# Driver code
n = 3
k = 56
print(minimum_sum(n, k))
# This code is contributed by mohit kumar 29
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimized sum
static int minimum_sum(int n, int k)
{
// If k is divisible by n
// then the answer will be 0
if (k % n == 0)
return 0;
// Else the answer will be 1
return 1;
}
// Driver code
static public void Main ()
{
int n = 3, k = 56;
Console.Write(minimum_sum(n, k));
}
}
// This code is contributed By Tushil
输出:
1