알고리즘/HackerRank

Counting Valleys

webmaster 2021. 11. 18. 17:31
728x90

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

 

Counting Valleys | HackerRank

Count the valleys encountered during vacation.

www.hackerrank.com

  • 문제
    • 문제
    • 수면 안으로 들어간 횟수를 계산해서 리턴해 주는 문제이다.

풀이

  • 초기 기준 수면선의 위치를 0 으로 세팅후 for문을 돌면서 0에서 -1로 갔을때에 결과값에 1을 더해준다.
  • 결과를 리턴한다.
  • public static int countingValleys(int steps, String path) {
            int n = 0;//수면선
            int answer = 0;//결과
            for(int i=0;i<steps;++i){
                char c = path.charAt(i);//올라가는지 내려가는지 ('U', 'D')
                if(c == 'U'){//올라갈 경우
                    n++; // 수면선 증가
                }else{ // 내려갈 경우
                    if(n == 0){ // 0에서 내려갈경우 즉, 0 -> -1 (잠수)
                        answer++;
                    }
                    n--;
                }
            }
            return answer;
        }
728x90

'알고리즘 > HackerRank' 카테고리의 다른 글

Arrays Left Rotation  (0) 2021.11.18
2D Array - DS  (0) 2021.11.18
Repeated String  (0) 2021.11.18
Jumping on the Clouds  (0) 2021.11.18
Sales by Match  (0) 2021.11.18