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
5
5 7 10 5 15
2 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<bits/stdc++.h>
using namespace std;
int main()
{
int n,k,steps=0;
cin>>n;
int i,a[n],b[n];
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
cin>>b[i];
for(i=0;i<n-1;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<n-1;i++)
{
while(a[n-1]!=a[i])
{
if(a[i]<=0)
{
cout<<"-1"<<endl;;
exit(0);
}
if(a[n-1]<a[i])
{
a[i]=a[i]-b[i];
steps++;
}
if(a[n-1]>a[i])
{
a[n-1]=a[n-1]-b[n-1];
steps++;
}
}
}
cout<<steps;
return 0;
}

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<n-1;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<n-1;i++)
{
while(a[n-1]!=a[i])
{
if(a[i]<=0)
{
printf("-1");
exit(0);
}
if(a[n-1]<a[i])
{
a[i]=a[i]-b[i];
steps++;
}
if(a[n-1]>a[i])
{
a[n-1]=a[n-1]-b[n-1];
steps++;
}
}
}
printf("%d",steps);
return 0;
}

recommended post:-