Algorithm/Programmers

[JavaScript] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ž…๊ตญ์‹ฌ์‚ฌ

๊ฐœ๋ฐœ๊ฐœ๊ตด๐Ÿธ 2022. 8. 27. 17:52

[๋ฌธ์ œ]

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

 

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

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

programmers.co.kr

 

[ํ’€์ด]

์ด๋ถ„ํƒ์ƒ‰์„ ์ด์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€์ดํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

์˜ˆ์ œ ์ฒ˜๋Ÿผ n์ด 6์ด๊ณ , time๊ฐ€ [7, 10] ์ด๋ผ๋ฉด, ์ตœ๋Œ€ ์‹ฌ์‚ฌ ์‹œ๊ฐ„์€ 10*6 = 60๋ถ„์ด๋ฉ๋‹ˆ๋‹ค.

 

์ตœ๋Œ€ ์‹ฌ์‚ฌ ์‹œ๊ฐ„ 60์„ ๊ธฐ์ค€์œผ๋กœ ์Šน๊ฐ์„ ์‹ฌ์‚ฌํ•œ๋‹ค๋ฉด ์‹ฌ์‚ฌ ๊ฐ€๋Šฅ ์Šน๊ฐ์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

60 / 7 = 8๋ช… + 60 / 10 = 10๋ช… = 18๋ช…

 

ํ•˜์ง€๋งŒ, ์ตœ์†Œ ์‹œ๊ฐ„์œผ๋กœ 6๋ช…์˜ ์Šน๊ฐ์„ ๋ชจ๋‘ ์‹ฌ์‚ฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ, left = 1, right = 60์œผ๋กœ ์ด๋ถ„ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

 

mid = (1 + 60)/2 = 30์œผ๋กœ ์‹œ์ž‘ํ•˜์—ฌ ์•„๋ž˜์™€ ๊ฐ™์ด ์ด๋ถ„ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

  • mid์‹œ๊ฐ„ ๊ธฐ์ค€์œผ๋กœ ์‹ฌ์‚ฌ ๊ฐ€๋Šฅ ์Šน๊ฐ์ด 6๋ณด๋‹ค ์ž‘๋‹ค๋ฉด, left = mid + 1๋กœ ๊ฐฑ์‹ 
  • mid์‹œ๊ฐ„ ๊ธฐ์ค€์œผ๋กœ ์‹ฌ์‚ฌ ๊ฐ€๋Šฅ ์Šน๊ฐ์ด 6๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๋‹ค๋ฉด, right = mid - 1๋กœ ๊ฐฑ์‹ 

๋”ฐ๋ผ์„œ ์ตœ์ข…์ ์œผ๋กœ left์— ์ตœ์†Œ ์‹œ๊ฐ„์ด ์ €์žฅ๋˜๊ฒŒ ๋˜๊ณ , ์ด 28๋ถ„์œผ๋กœ ๋ชจ๋“  ์Šน๊ฐ์„ ์‹ฌ์‚ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

[์ฝ”๋“œ]

function solution(n, times) {
    var answer = 0;
    times.sort((a, b) => a - b);
    
    const max = times[times.length -1]*n;
    
    let left = 1;
    let right = max;
    
    while(left <= right) {
        let mid = Math.floor((left + right)/2);
        
        let count = 0;
        for(let i=0;i<times.length;i++) {
            count += Math.floor(mid/times[i]);
        }
        
        if(count >= n) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    
    answer = left;
    
    return answer;
}