백준 오르막길

KIMYEONGJUN·2025년 3월 14일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

첫째 줄에 상근이가 측정한 높이의 수이자 수열의 크기인 N(1 ≤ N ≤ 1000)이 주어진다.
둘째 줄에는 N개의 양의 정수 Pi(1 ≤ Pi ≤ 1000)가 주어진다.
각 숫자는 상근이가 측정한 높이이다.

첫째 줄에 가장 큰 오르막길의 크기를 출력한다.
만약 오르막길이 없는 경우에는 0을 출력한다.

내가 이 문제를 보고 생각해본 부분

입력 처리: BufferedReader와 StringTokenizer를 사용하여 입력을 받는다.
변수 초기화: maxUphill 변수를 사용하여 가장 큰 오르막길의 크기를 저장한다.
오르막길 탐색:
반복문을 통해 현재 위치에서 다음 높이가 더 높은 경우를 찾아서 오르막길을 확장한다.
오르막길의 크기를 계산하여 maxUphill을 업데이트해준다.
결과 출력: 최종적으로 가장 큰 오르막길의 크기를 출력한다.

코드로 구현

package baekjoon.baekjoon_27;

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

// 백준 2846번 문제
public class Main960 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int N = Integer.parseInt(br.readLine());
        int[] heights = new int[N];
        StringTokenizer st = new StringTokenizer(br.readLine());

        for(int i = 0; i < N; i++) {
            heights[i] = Integer.parseInt(st.nextToken());
        }

        int maxUphill = 0;
        int currentStart = 0;

        while(currentStart < N - 1) {
            if(heights[currentStart] < heights[currentStart + 1]) {
                int end = currentStart + 1;

                while(end < N && heights[end - 1] < heights[end]) {
                    end++;
                }

                int uphillSize = heights[end - 1] - heights[currentStart];
                maxUphill = Math.max(maxUphill, uphillSize);
                currentStart = end - 1; // 다음 탐색 시작 위치
            } else {
                currentStart++;
            }
        }

        sb.append(maxUphill).append("\n");
        System.out.print(sb);
        br.close();
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글