Number of steps | Practice problem hackerearth Solution

 Problem:-

You are given two arrays 

a1,a2,,an

 and 

b1,b2,,bn

. In each step, you can set 

ai=aibi

 if 

aibi

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

a

‘s equal.

Input format

  • First line: 
    n

     

  • Second line: 
    a1,a2,,an

  • Third line: 
    b1,b2,,bn

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

1n, ai, bi5000

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<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:-



Leave a Reply

Your email address will not be published.