Forming smallest array with given constraints
Last Updated :
17 Aug, 2022
Given three integers x, y and z (can be negative). The task is to find the length of the smallest array that can be made such that absolute difference between adjacent elements is less than or equal to 1, the first element of the array is x, having one integer y and last element z.
Examples:
Input : x = 5, y = 7, z = 11
Output : 7
The smallest starts with 5, having 7, ends
with 11 and having absolute difference 1
is { 5, 6, 7, 8, 9, 10, 11 }.
Input : x = 3, y = 1, z = 2
Output : 4
The array would become { 3, 2, 1, 2 }
The idea is to consider the number line since the difference between adjacent elements is 1 so to move from X to Y all numbers between x and y have to be covered and to end the array with integer z, so move from element y to element z.
So, the length of the smallest array that can be formed will be the number of points that will be covered from x to z i.e.
1 + abs(x - y) + abs(y - z) (1 is added to count point x).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumLength( int x, int y, int z)
{
return 1 + abs (x - y) + abs (y - z);
}
int main()
{
int x = 3, y = 1, z = 2;
cout << minimumLength(x, y, z);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int minimumLength( int x,
int y, int z)
{
return 1 + Math.abs(x - y)
+ Math.abs(y - z);
}
public static void main(String[] args)
{
int x = 3 , y = 1 , z = 2 ;
System.out.println(
minimumLength(x, y, z));
}
}
|
Python 3
def minimumLength(x, y, z):
return ( 1 + abs (x - y)
+ abs (y - z))
x = 3
y = 1
z = 2
print (minimumLength(x, y, z))
|
C#
using System;
class GFG {
static int minimumLength( int x,
int y,
int z)
{
return 1 + Math.Abs(x - y)
+ Math.Abs(y - z);
}
public static void Main()
{
int x = 3, y = 1, z = 2;
Console.WriteLine(minimumLength(x, y, z));
}
}
|
PHP
<?php
function minimumLength( $x , $y , $z )
{
return 1 + abs ( $x - $y ) +
abs ( $y - $z );
}
$x = 3;
$y = 1;
$z = 2;
echo minimumLength( $x , $y , $z );
?>
|
Javascript
<script>
function minimumLength(x, y, z)
{
return 1 + Math.abs(x - y) + Math.abs(y - z);
}
var x = 3, y = 1, z = 2;
document.write( minimumLength(x, y, z));
</script>
|
Complexity Analysis:
- Time Complexity: O(1)
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...