๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

๋งˆ๊ตฌ๊ฐ„ ์ •ํ•˜๊ธฐ(๊ฒฐ์ •์•Œ๊ณ ๋ฆฌ์ฆ˜) ๋ณธ๋ฌธ

๐Ÿ“š Language & CS knowledge/Algorithm (๊ธฐ์ดˆ๋ฌธ์ œํ’€์ด)

๋งˆ๊ตฌ๊ฐ„ ์ •ํ•˜๊ธฐ(๊ฒฐ์ •์•Œ๊ณ ๋ฆฌ์ฆ˜)

Daehyunii 2022. 9. 6. 19:04

๋ฌธ์ œ(์ถœ์ฒ˜ : ์ธํ”„๋Ÿฐ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด ๊ฐ•์˜, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ)

 

N๊ฐœ์˜ ๋งˆ๊ตฌ๊ฐ„์ด ์ˆ˜์ง์„ ์ƒ์— ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ๋งˆ๊ตฌ๊ฐ„์€ x1, x2, x3, ......, xN์˜ ์ขŒํ‘œ๋ฅผ ๊ฐ€์ง€๋ฉฐ, ๋งˆ ๊ตฌ๊ฐ„๊ฐ„์— ์ขŒํ‘œ๊ฐ€ ์ค‘๋ณต๋˜๋Š” ์ผ์€ ์—†์Šต๋‹ˆ๋‹ค. ํ˜„์ˆ˜๋Š” C๋งˆ๋ฆฌ์˜ ๋ง์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ, ์ด ๋ง๋“ค์€ ์„œ๋กœ ๊ฐ€๊นŒ์ด ์žˆ๋Š” ๊ฒƒ์„ ์ข‹์•„ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ฐ ๋งˆ๊ตฌ๊ฐ„์—๋Š” ํ•œ ๋งˆ๋ฆฌ์˜ ๋ง๋งŒ ๋„ฃ์„ ์ˆ˜ ์žˆ๊ณ , ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€๊ฐ€ ๋˜๊ฒŒ ๋ง์„ ๋งˆ๊ตฌ๊ฐ„์— ๋ฐฐ์น˜ํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค. C๋งˆ๋ฆฌ์˜ ๋ง์„ N๊ฐœ์˜ ๋งˆ๊ตฌ๊ฐ„์— ๋ฐฐ์น˜ํ–ˆ์„ ๋•Œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€๊ฐ€ ๋˜๋Š” ๊ทธ ์ตœ๋Œ€ ๊ฐ’์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=200,000)๊ณผ C(2<=C<=N)์ด ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๋‘˜์งธ ์ค„์— ๋งˆ๊ตฌ๊ฐ„์˜ ์ขŒํ‘œ xi(0<=xi<=1,000,000,000)๊ฐ€ ์ฐจ๋ก€๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

 

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•˜์„ธ์š”.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1

5 3

1 2 8 4 9

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ 1

3

 

Tip

 

๋ฌธ์ œํ’€์ด

//๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ๋‹ต
function count(arr,distance){  //5
    let endPoint = arr[0];
    let cnt = 1;
    for(let i = 1 ; i < arr.length ; i++){
        if(arr[i]-endPoint >= distance){
            cnt++;
            endPoint = arr[i];
        }
    }
    return cnt;
}


function solution(arr,horses){
    let answer = 0;
    arr.sort((a,b) => a-b);

    let lt = 1; // ๋งˆ์„ ๋ฐฐ์น˜ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋Š” 1์ž„
    let rt = Math.max(...arr); // ๋ฐฐ์—ด์˜ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๊ทธ๋ƒฅ ๋„ฃ์Œ
    console.log('lt',lt);
    console.log('rt',rt);

    while(lt <= rt){
        let mid = Math.floor((lt+rt)/2);
        if(count(arr,mid) >= horses){ //ํ•„์š”ํ•œ ๋งˆ๋ฆฌ์ˆ˜ ๋งŒํผ ์ œ๋Œ€๋กœ ๋ฐฐ์น˜๊ฐ€ ๋œ ๊ฒฝ์šฐ์ž„, ๊ฑฐ๋ฆฌ๋ฅผ ๋Š˜๋ ค์•ผํ•จ
            if(mid > answer) answer = mid;
            lt = mid+1;
        }else{ //ํ•„์š”ํ•œ ๋งˆ๋ฆฌ์ˆ˜ ๋งŒํผ ์ œ๋Œ€๋กœ ๋ฐฐ์น˜๊ฐ€ ๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ์ž„, ๊ฑฐ๋ฆฌ๋ฅผ ์ค„์—ฌ์•ผํ•จ
            rt = mid-1;
        } 
    }

    return answer;
}


let arr = [1,2,8,4,9];
console.log(solution(arr,3));