We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticintcountingValleys(intsteps,stringpath){// Create stack to track mountains and valleysStack<char>altitudes=newStack<char>();intvalleys=0;// Counter for valleys// Go through all the stepsfor(ints=0;s<steps;s++){charstep=path[s];// Grab next step// Check if there its the begining of a M or a V// or if it matches the last stepif(altitudes.Count==0||step==altitudes.Peek())altitudes.Push(path[s]);// if it does, add it to the stackelse{// if it doesn't, take the last step to matchaltitudes.Pop();// if we're back at sea level and the last step// was up, then we exited a valleyif(altitudes.Count==0&&step=='U')valleys++;}}// return the number of valleys crossedreturnvalleys;}
Cookie support is required to access HackerRank
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 →
In C#