2021 Updated The Hurdle Race Hackerrank Solution in C++

 

        The Hurdle Race is an HackerRank problem of Easy difficulty level. If you correctly solve this code you get 15 points. 

        This problem is based on a video game, in which the character is running a hurdle race. The character can jump a maximum height of "K" and total "N" hurdles are present.

        The maximum height character can jump is constant throughout the game. But there exists an magic potion, if you drink one dose of the potion your character height increases by "one unit". You need to calculate the no of doses required to complete the hurdle race. 

        If the character can jump the tallest hurdle without any dose of potion print "Zero" else print the no of doses required to complete the race.

The solution is explained in below parts 

  1.  Logic
  2.  Example

  1.  C++ Code

Logic : 

  • Take no of hurdles and max height.
  • Take all the heights and store in array.
  • Sort the array.
  • Compare last element of array with max height
  • If less or equal print zero
  • else subtract max height(k) from last element and print the output.

Example :

 Input : 

 5 4
 1 6 3 5 2

Output :

 2

No. of Hurdles = 5
Tallest Hurdle  = 6

Maximum Height Character can Jump = 4

No. of Doses Required = Tallest Hurdle - Max Height Player can Jump
No. of Doses Required = 6 - 4 = 2

No. of Doses Required to complete the Race are 2.
 

Code :


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

int main(){
    int n,k;
    cin>>n>>k;
    
    int a[n];
    
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    
    int x= sizeof(a)/sizeof(a[0]);
    
    sort(a, a+x);
    
    if(a[n-1]<=k){
        cout<<"0"<<endl;
    }
    else{
        cout<<a[n-1]-k<<endl;
    }
}





    Post a Comment

    0 Comments