๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์•Œ๊ณ ๋ฆฌ์ฆ˜

[2019 ์นด์นด์˜ค ๊ฐœ๋ฐœ์ž ๊ฒจ์šธ ์ธํ„ด์‹ญ] ์ง•๊ฒ€๋‹ค๋ฆฌ ๊ฑด๋„ˆ๊ธฐ

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/64062

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

์†Œ์Šค์ฝ”๋“œ

import java.util.Arrays;

public class Solution {

    public int solution(int[] stones, int k) {

        int answer = 0;
        int start = Arrays.stream(stones).min().getAsInt();
        int end = Arrays.stream(stones).max().getAsInt();

        while(start <= end) {

            int mid = (start + end) / 2;

            if(cross(mid, stones.clone(), k)) {
                answer = mid;
                start = mid + 1;
            } else {
                end = mid - 1;
            }

        }

        return answer;
    }

    public boolean cross(int num, int[] stones, int k) {

        Arrays.setAll(stones, i -> (stones[i] - num + 1)); // --- (1)

        int max = 0, cnt = 0;

        for(int stone : stones) {
            if(cnt > 0 && stone > 0) {
                max = Math.max(max, cnt);
                cnt = 0;
            } else if(stone <= 0) {
                cnt++;
            }
        }

        return Math.max(max, cnt) < k;
    }

}

 

ํšŒ๊ณ 

-  ์ด๋ถ„ํƒ์ƒ‰์œผ๋กœ ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ํ•™์ƒ ์ˆ˜๋ฅผ ์ฐพ์•„๊ฐ„๋‹ค.

- cross์—์„œ๋Š” num๋ฒˆ์งธ ํ•™์ƒ์ด ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š”์ง€๋งŒ ํŒ๋‹จํ•˜๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์—, (1)์—์„œ๋Š” (num-1)๋ฒˆ์งธ ํ•™์ƒ๊นŒ์ง€ ๊ฑด๋„œ์„ ๋•Œ        stone๋“ค์˜ ์ƒํƒœ๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค.

- ์ดํ›„ num๋ฒˆ์งธ ํ•™์ƒ์ด ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธํ•ด์ค€๋‹ค.