[BOJ 14719] ๋น—๋ฌผ

1. ๋ฌธ์ œ : Link

์ง€ํ˜•์˜ ๋†’์ด๊ฐ€ ๋ฐฐ์—ด๋กœ ์ฃผ์–ด์กŒ์„๋•Œ ๊ณ ์ธ ๋น—๋ฌผ์˜ ์–‘์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ

 

2. ํ’€์ด

ํ˜„์žฌ ๋†’์ด๋ฅผ ์ค‘์‹ฌ์œผ๋กœ ์–‘์˜† ์ตœ๋Œ€๋†’์ด๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•

 

3. ์ฝ”๋“œ

import java.util.*;

class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int H = sc.nextInt();
        int W = sc.nextInt();
        int[] arr = new int[W];
        int answer = 0;
        for (int i = 0; i < W; i++) {
            arr[i] = sc.nextInt();
        }
        for (int i = 1; i < W - 1; i++) {
            int current = arr[i]; //ํ˜„์žฌ ๋ฒฝ ๋†’์ด
            int leftMax = current; //์™ผ์ชฝ ๋ฒฝ ์ตœ๋Œ€๋†’์ด
            int rightMax = current; //์˜ค๋ฅธ์ชฝ ๋ฒฝ ์ตœ๋Œ€๋†’์ด
            for (int k = i - 1; k >= 0; k--) { //์™ผ์ชฝ ์ตœ๋Œ€๋ฒฝ ๋†’์ด ํƒ์ƒ‰
                if (arr[k] > current) {
                    leftMax = Math.max(leftMax, arr[k]);
                }
            }
            for (int k = i + 1; k < W; k++) { //์˜ค๋ฅธ์ชฝ ์ตœ๋Œ€๋ฒฝ ๋†’์ด ํƒ์ƒ‰
                if (arr[k] > current) {
                    rightMax = Math.max(rightMax, arr[k]);
                }
            }
            if (Math.min(leftMax, rightMax) > current) { // ํ˜„์žฌ ๋ฒฝ๋ณด๋‹ค ๋†’์€ ๋ฒฝ์ด ์–‘์ชฝ์— ์žˆ๋Š” ๊ฒฝ์šฐ
                answer += (Math.min(leftMax, rightMax) - arr[i]);
            }
        }
        System.out.println(answer);
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ