When submitting a solution in C++, please select either C++14 (GCC 6-32) or C++17 (GCC 7-32) as your compiler. ×

ghoshsai5000's blog

By ghoshsai5000, history, 7 years ago, In English

Here is the link for the problem with CodeChef problem Carvans.

Here's my solution. ... I am unable to find any bugs. Please help me debug it and tell me what is wrong with it.

#include <stdio.h>
#include <algorithm>

using namespace std;

void solve()
{
    int previous_car_speed = 1e9, current_car_speed, number_of_cars, current_car_max_speed;;
    scanf("%d", &number_of_cars);

   int no_of_cars_at_max_speed = 0;
    for(int i = 1; i <= number_of_cars; i++)
   {
        scanf("%d", &current_car_max_speed);

        current_car_speed = min(previous_car_speed, current_car_max_speed);

        no_of_cars_at_max_speed += (current_car_speed == current_car_max_speed);

        previous_car_speed = current_car_speed;
   }

   printf("%d\n", no_of_cars_at_max_speed);
}

 int main()
 {
    int no_of_test_cases;
    scanf("%d", &no_of_test_cases);

    while(no_of_test_cases--)
        solve();

    return 0;
}
  • Vote: I like it
  • -11
  • Vote: I do not like it

| Write comment?
»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by ghoshsai5000 (previous revision, new revision, compare).

»
7 years ago, # |
  Vote: I like it +3 Vote: I do not like it

You might want to change your loop to :

for(int i = 1; i <= number_of_cars; i++) { scanf("%d", &current_car_speed);

current_car_max_speed = min(current_car_speed, current_car_max_speed);

    no_of_cars_at_max_speed += (current_car_speed <= current_car_max_speed);

}

Don't forget to initialize current_car_max_speed to INT_MAX.

The logic behind this is you have to compare every car's speed to the max allowable speed and change the max allowable speed to the minimum of the current and max in every iteration.

Test Run the code for : 1 5 4 5 1 2 3

You will get it.

Happy Coding :)