Hackerrank's Problem Solving solutions( Picking Numbers, The Hurdle Race, Designer PDF Viewer ) :
Problem 25: Picking Numbers
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
In this question we have to find the length of the subarray from the given array which includes elements such that absolute difference between any two elements is less or equal to 1 i.e abs(x-y)<=1 .
What i have done here is we will count the occurrence of every element of the vector represented by c and then all the occurrences of the (element-1) represented by d so that we will cover only the elements whose absolute difference is less than or equal to 1 .
For example : v = { 1 , 1 , 2 , 2 , 4 , 4 , 5 , 5 , 5 }
The first iteration of the for loop will consider the first element of the vector ,
Therefore , c = 2 ( the number of occurrences of 1)
d = 0 ( the number of occurrences of 0 i.e 1-1)
now c = c+d ==> c = 2 ;
This process makes sure that we are considering only those elements whose absolute difference is less than or equal to 1.
Similarly this is done with each element of the array or vector till we get the maximum value of c ( of course it will be the length of the subarray or i say number of elements from array which are needed to make the subarray )
Problem 26: The Hurdle Race
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
This code is simple. There's no need for any explanation.
Comments
Post a Comment