ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

[๋ฌธ์ œ]

https://school.programmers.co.kr/learn/courses/30/lessons/12979#

 

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

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

programmers.co.kr

 

[ํ’€์ด]

์ „ํŒŒ๋ ฅ์ดw์ธ ๊ฒฝ์šฐ, ์ตœ๋Œ€ 2*w + 1 ๊ฑฐ๋ฆฌ๋งŒํผ ์•„ํŒŒํŠธ๋“ค์—๊ฒŒ ์ „ํŒŒ๊ฐ€ ๋„๋‹ฌ๋ฉ๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ์ „ํŒŒ๊ฐ€ ๋„๋‹ฌํ•˜์ง€ ์•Š์€ ์—ฐ์†๋œ ์•„ํŒŒํŠธ์— ์ตœ์†Œ์˜ ๊ธฐ์ง€๊ตญ์œผ๋กœ ์ „ํŒŒ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

  • Math.ceil(์—ฐ์†๋œ ์•„ํŒŒํŠธ ๊ธธ์ด/(2*w+1))

์˜ˆ์‹œ 1๋ฒˆ๊ณผ ๊ฐ™์ด w=1์ธ ๊ฒฝ์šฐ ์ „ํŒŒ๊ฐ€ ๋„๋‹ฌํ•˜์ง€ ์•Š์€ ์—ฐ์†๋œ ์•„ํŒŒํŠธ์˜ ๊ธธ์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

 

๋”ฐ๋ผ์„œ Math.ceil(2/3) +  Math.ceil(4/3) = 1 + 2 = 3์ด ์ •๋‹ต์ด ๋ฉ๋‹ˆ๋‹ค.

 

 

์ด๋ฅผ ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ํ˜„์žฌ ๊ธฐ์ค€์  idx = 1๋กœ ์ดˆ๊ธฐํ™”ํ•œ ํ›„, stations๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉฐ ์•„ํŒŒํŠธ์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•ฉ๋‹ˆ๋‹ค.

  • start = 3, end = 5 ์ด๋ฏ€๋กœ ๊ธธ์ด๋Š” start - idx = 2์ด๋ฉฐ, idx = end + 1 = 6์œผ๋กœ ๊ฐฑ์‹ 
  • start = 10, end = 11์ด๋ฏ€๋กœ ๊ธธ์ด๋Š” start - idx = 4์ด๋ฉฐ, idx = end + 1 = 12์œผ๋กœ ๊ฐฑ์‹ 

๋”ฐ๋ผ์„œ ์ „ํŒŒ๊ฐ€ ์—†๋Š” ์•„ํŒŒํŠธ์˜ ๊ธธ์ด๋Š” 2์™€ 4์ธ๊ฒƒ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

[์ฝ”๋“œ]

function solution(n, stations, w) {
    var answer = 0;

    let idx = 1;
    stations.forEach((station) => {
        let [start, end] = [station - w, station + w];
        if(idx > n) {
            return answer;
        }
        if(start > idx) {
            answer += Math.ceil((start - idx)/(2*w+1));
        }
        idx = end+1;
    })
    if(idx <= n) {
        answer += Math.ceil((n - idx + 1)/(2*w+1));
    }
    return answer;
}