Number of steps

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.

Example:

Input: n = 5, a[n] = {5, 7, 10, 5, 15}, b[n] = {2, 2, 1, 3, 5};
Output: 8

Approach

C++

#include <iostream>
using namespace std;

void numberOfSteps(int n, int a[], int b[])
{
    int min = 5000;
    bool flag = false;
    int steps;
    for (int i = 0; i < n; i++)
    {

        if (a[i] < min)
            min = a[i];
    }

    for (int i = 0; i < n; i++)

    {

        while (a[i] > min)

        {

            a[i] -= b[i];

            steps++;

            if (a[i] < 0)

            {

                flag = true;

                break;
            }
        }

        if (flag)

            break;

        if (a[i] < min)

            min = a[i];
    }

    for (int i = 1; i < n; i++)

    {

        if (a[i] != a[i - 1])

            flag = true;
    }

    if (flag)

        cout << "-1";

    else

        cout << steps;
}
int main()
{
    int n = 5;

    int a[n] = {5, 7, 10, 5, 15};
    int b[n] = {2, 2, 1, 3, 5};

    numberOfSteps(n, a, b);

    return 0;
}


No comments:

Post a Comment