# Number of steps | Practice problem hackerearth Solution

Problem:-

You are given two arrays

${a}_{1},{a}_{2},\dots ,{a}_{n}$

and

${b}_{1},{b}_{2},\dots ,{b}_{n}$

. In each step, you can set

${a}_{i}={a}_{i}-{b}_{i}$

if

${a}_{i}\ge {b}_{i}$

. Determine the minimum number of steps that are required to make all

$a$

‘s equal.

Input format

• First line:
$n$

• Second line:
${a}_{1},{a}_{2},\dots ,{a}_{n}$

• Third line:
${b}_{1},{b}_{2},\dots ,{b}_{n}$

Output format

Print the minimum number of steps that are required to make all

$a$

‘s equal. If it is not possible, then print -1.

Constraints

Sample input

2
5 6
4 3

Sample output

-1

Sample Input
`55 7 10 5 152 2 1 3 5`
Sample Output
`8`
Time Limit: 1
Memory Limit: 256
Source Limit:

Code:-

Here I am going to give you two solution first by using C language and second by using c++ language . You can submit the second solution in the c++ , c++14 and c++17 also.

So let’s go for the code.

C++ (Code):-

This solution you can submit in the c++ ,c++14 and c++17 . it is acceptable in all these languages.

#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n], b[n];
int min = 5000;
bool hmm = false;
int steps;
for(int i = 0; i < n; i++)
{
cin >> a[i];
if(a[i] < min)
min = a[i];
}
for(int i = 0; i < n; i++)
{
cin >> b[i];
}
for(int i = 0; i < n; i++)
{
while(a[i] > min)
{
a[i] -= b[i];
steps++;
if(a[i] < 0)
{
hmm = true;
break;
}
}
if(hmm)
break;
if(a[i] < min)
min = a[i];
}
for(int i = 1; i < n; i++)
{
if(a[i] != a[i1])
hmm = true;
}
if(hmm)
cout << “-1”;
else
cout << steps;
}

C (Code):-

#include<stdio.h>
int main()
{
int n,k,steps=0;
scanf(“%d”,&n);
int i,a[n],b[n];
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
for(i=0;i<n1;i++)
{
if(a[i]<a[i+1])
{
k=a[i];
a[i]=a[i+1];
a[i+1]=k;
k=b[i];
b[i]=b[i+1];
b[i+1]=k;
}
}
for(i=0;i<n1;i++)
{
while(a[n1]!=a[i])
{
if(a[i]<=0)
{
printf(“-1”);
exit(0);
}
if(a[n1]<a[i])
{
a[i]=a[i]-b[i];
steps++;
}
if(a[n1]>a[i])
{
a[n1]=a[n1]-b[n1];
steps++;
}
}
}
printf(“%d”,steps);
return 0;
}

recommended post:-