Counting Valleys

HeeSeong·2021년 6월 27일
0

HackerRank

목록 보기
2/18
post-thumbnail

🔗 문제 링크

https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup


❔ 문제 설명


An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphill, U, or a downhill, D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following terms:

A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.

Example

steps = 8 path = [DDUUUUDD]

The hiker first enters a valley units deep. Then they climb out and up onto a mountain units high. Finally, the hiker returns to sea level and ends the hike.

Function Description

Complete the countingValleys function in the editor below.

countingValleys has the following parameter(s):

  • int steps: the number of steps on the hike

  • string path: a string describing the path

Returns

  • int: the number of valleys traversed

Input Format

The first line contains an integer steps, the number of steps in the hike.
The second line contains a single string path, of steps characters that describe the path.


⚠️ 제한사항


  • 2steps1062≤ steps ≤10^6

  • path[i]UDpath[i] ∈ {UD}



💡 풀이 (언어 : Java)


해발 0 이상에서 미만으로 떨어지는 시점을 체킹해야하는 알고리즘을 짜야했다. 해발 0미만만 체킹하면 계속 카운팅되어 방문횟수가 안되기 때문에, valley를 떠나고 다시 0미만으로 진입하는 시점에 1번씩 체킹해주어야 한다. 해발 계산해서 계곡 진입했는지 여부는 나중에 체킹해주어 방문 카운팅 시에는 첫 진입시에 valley가 false로 여태 0 이상이였던 시점만 answer을 카운팅할 수 있다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    private static int countingValleys(int n, String upDown) {
        boolean isValley = false;
        int seaLevel = 0;
        int answer = 0;
        
        for (int i = 0; i < n; i++) {
            char step = upDown.charAt(i);
            if (step == 'U') {
                seaLevel += 1;
            } else {
                seaLevel -= 1;
                if (!isValley && seaLevel < 0) {
                    answer += 1;
                }
            }
            isValley = (seaLevel < 0) ? true : false;            
        }
        return answer;
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String upDown = br.readLine();
        System.out.println(countingValleys(n, upDown));
    }
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글