using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { Console.ReadLine(); var steps = Console.ReadLine(); var heights = new int[steps.Length + 1]; var current = 0; for (var i = 0; i < steps.Length; i++) { heights[i] = current; current += steps[i] == 'U' ? 1 : -1; } heights[steps.Length] = current; // keep only the negative heights (and zero) var below = heights.Where(it => it <= 0).ToArray(); // we always start at sea level (zero) // 0, 0... can indicate a mountain // 0, -1, ..., 0 indicates a valley var count = 0; var inValley = false; for (var i = 0; i < below.Length; i++) { // below[i] can only be negative or zero if (below[i] < 0) inValley = true; else if (inValley) { inValley = false; count++; } } Console.WriteLine(count); } }