Number of steps (Hackerearth)

Problem

You are given two arrays a1,a2,…,an and b1,b2,…,bn. In each step, you can set ai=ai−bi if ai≥bi. 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

1≤n, ai, bi≤5000

Sample input

2

5 6

4 3

Sample output

-1

Approach -> We need to make sure that all the elements of the array A are equal, we will set the first value of the array A[] as minimum and iterate a loop to find the min value in the array, Once found we will iterate another loop to check array values higher than min value and perform a[i]-b[i] operation until they are equal to min. A step variable will be created to increment after every operation.

CODE->

#include <stdio.h>

int main(){
int n,i,a[5000],b[5000],min=a[0],steps=0,f=0;
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<n;i++) scanf("%d",&b[i]);
min=a[0];
for(i=1;i<n;i++){
if(a[i]<min)min=a[i];
}
for(i=0;i<n;i++){
while(a[i]>min && b[i]!=0){
a[i]-=b[i];
steps++;
}
if(a[i]<0){
f=1;
break;
}
if(a[i]<min){
min=a[i];
i=-1;
}
}
if(f!=1) printf("%d",steps);
else printf("-1");
}

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)