Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I loop throught all steps and remeber the level from the sea (level). If it is D, I decrement by 1, if U increment by 1.
When such situation happen that actual sea level is 0 and current step is U, then I found new valley and increate the count of valley variable.
I created solution in:
All solutions are also available on my GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val steps = lines.tail.head var valleys = 0 var seaLevel = 0 steps.foreach(c => { if(c == 'D') { seaLevel -= 1 } else { seaLevel += 1 } if(seaLevel == 0 && c == 'U') { valleys += 1 } }) println(valleys) } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); String steps = stdin.nextLine(); int valleys = 0; int seaLevel = 0; for(int i = 0; i < tests; i++) { char c = steps.charAt(i); if(c == 'D') { seaLevel -= 1; } else { seaLevel += 1; } if(seaLevel == 0 && c == 'U') { valleys += 1; } } System.out.println(valleys); stdin.close(); } } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
'use strict'; const processData = input => { const lines = input.split('\n'); const steps = lines[1]; let valleys = 0; let seaLevel = 0; for(let i = 0; i < steps.length; i++) { let c = steps.charAt(i); if(c == 'D') { seaLevel -= 1; } else { seaLevel += 1; } if(seaLevel == 0 && c == 'U') { valleys += 1; } } console.log(valleys); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |