You are viewing a single comment's thread. Return to all comments →
Go Golang Solution O(n)
Iterate through the path, adjust your altitude according to the current step(+1 for U and -1 for D)
Anytime you come out of a valley and return to sea level (altitude 0) you can count a valley.
func countingValleys(steps int32, path string) (count int32) { altitude, last := 0, 0 for i := 0;i < int(steps);i++ { last = altitude if rune(path[i]) == 'D' { altitude-- } else if rune(path[i]) == 'U' { altitude++ } if i != 0 && last < 0 && altitude == 0 { count++ } } return }
Seems like cookies are disabled on this browser, please enable them to open this website
Counting Valleys
You are viewing a single comment's thread. Return to all comments →
Go Golang Solution O(n)
Iterate through the path, adjust your altitude according to the current step(+1 for U and -1 for D)
Anytime you come out of a valley and return to sea level (altitude 0) you can count a valley.