Speed

The rash is known for his love for racing sports. He is an avid Formula 1 fan. He went to watch this year's Indian Grand Prix in New Delhi. He noticed that one segment of the circuit was a long straight road. It was impossible for a car to overtake other cars on this segment. Therefore, a car had to lower down its speed if there was a slower car in front of it. While watching the race, Rash started to wonder how many cars were moving at their maximum speed. Formally, you're given the maximum speed of N cars in the order they entered the long straight segment of the circuit. Each car will prefer to move at its maximum speed. If that's not possible because the front car is slow, it might have to lower its speed. It still moves at the fastest possible speed while avoiding any collisions. For the purpose of this problem, you can assume that the straight segment is infinitely long. Count the number of cars that were moving at their maximum speed on the straight segment.

Example:

Input:  n = 3, arr = [8,3,6]
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long long speed(long long nlong long a[])
{
    long long ans = 1;
    for (long long i = 1i < ni++)
    {
        if (a[i] <= a[i - 1])
        {
            ans++;
        }
        else
            a[i] = a[i - 1] - 1;
    }
    return ans;
}
int main()
{

    long long n = 3;
    long long a[n] = {836};

    cout << speed(na<< "\n";

    return 0;
}


No comments:

Post a Comment