Check out the counting valleys question here: Hackerrank question
The picturization of the problem:
Suppose the input is: UDDDUDUU
Then,
Answer: Valley level is 1. Because hiker stepped this way only.To solve this problem:
Initially, assumed U = 1, D = -1 & altitude=0
Then, iterated till total steps-1. Whenever altitude(height) that is sea level is 0 & the last step is 'U" I have incremented the valley by 1 (because valley level is considered only when hiker's last step is 'U" & at the sea level).
When all the elements are traversed it returned the final valley's value that's our final result.
Solution:
def countingValleys(steps, path):
# Write your code here
altitude = 0
valley = 0
dict = {
"U": 1,
"D": -1
}
for eachstep in range(steps):
altitude += dict[path[eachstep]] # calculating hiker's each step
if altitude == 0 and path[eachstep] == "U":
valley += 1
return valley
No comments:
Post a Comment