📜  序号为K且连续元素之间的绝对差的最小和为最小

📅  最后修改于: 2021-04-22 01:24:51             🧑  作者: Mango

给定两个整数NK ,任务是找到一个长度为N的整数序列,以使序列中所有元素的总和为K,并且所有连续元素之间的绝对差之和最小。打印此最小化的总和。

例子:

方法:可能有两种情况:

  1. K%N = 0时,答案将为0,因为K可以平均分为N个部分,即序列中的每个元素都将相等。
  2. 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