📌  相关文章
📜  在给定约束下形成最小数组

📅  最后修改于: 2021-05-07 07:15:12             🧑  作者: Mango

给定三个整数x,yz (可以为负)。任务是找到可以制成的最小数组的长度,以使相邻元素之间的绝对差小于或等于1,该数组的第一个元素为x,具有一个整数y,最后一个元素为z。

例子:

想法是考虑数字线,因为相邻元素之间的差为1,因此要从X移到Y,必须覆盖x和y之间的所有数字,并以整数z结束数组,因此要从元素y移到元素z 。
因此,可以形成的最小数组的长度将是从x到z覆盖的点数,即

1 + abs(x - y) + abs(y - z) (1 is added to count point x).
C++
// C++ program to find the length of 
// smallest array begin with x, having y,
// ends with z and having absolute difference 
// between adjacent elements <= 1.
#include 
using namespace std;
  
// Return the size of smallest 
// array with given constraint.
int minimumLength(int x, int y, int z)
{
    return 1 + abs(x - y) + abs(y - z);
}
  
// Drivers code
int main()
{
    int x = 3, y = 1, z = 2;
    cout << minimumLength(x, y, z);
  
    return 0;
}


Java
// Java program to find the length 
// of smallest array begin with x,
// having y, ends with z and having
// absolute difference between
// adjacent elements <= 1.
import java.io.*;
  
class GFG {
      
    // Return the size of smallest 
    // array with given constraint.
    static int minimumLength(int x,
                      int y, int z)
    {
        return 1 + Math.abs(x - y)
                 + Math.abs(y - z);
    }
      
    // Drivers code
  
    public static void main(String[] args)
    {
        int x = 3, y = 1, z = 2;
        System.out.println( 
              minimumLength(x, y, z));
    }
}
  
// This code is contributed by anuj_67.


Python 3
# Python 3 program to find
# the length of smallest 
# array begin with x, having
# y, ends with z and having
# absolute difference between
# adjacent elements <= 1.
  
# Return the size of smallest 
# array with given constraint.
def minimumLength(x, y, z):
  
    return (1 + abs(x - y) 
              + abs(y - z))
  
# Drivers code
x = 3
y = 1
z = 2
print(minimumLength(x, y, z))
  
# This code is contributed 
# by Smitha


C#
// C# program to find the length 
// of smallest array begin with x,
// having y, ends with z and having
// absolute difference between
// adjacent elements <= 1.
using System;
class GFG {
      
    // Return the size of smallest 
    // array with given constraint.
    static int minimumLength(int x,
                             int y,
                             int z)
    {
        return 1 + Math.Abs(x - y)
                 + Math.Abs(y - z);
    }
      
    // Driver Code
    public static void Main()
    {
        int x = 3, y = 1, z = 2;
        Console.WriteLine(minimumLength(x, y, z));
    }
}
  
// This code is contributed by anuj_67.


PHP


输出

4