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

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[์•Œ๊ณ ๋ฆฌ์ฆ˜ || ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ฒด์œก๋ณต

728x90

์ด๊ฑฐ ํ’€๊ธด ๋‚˜๋ฆ„ ๋นจ๋ฆฌ ํ’€์—ˆ๋Š”๋ฐ, 

์ฝ”๋“œ ์ •๋ฆฌํ•˜๋Š” ๊ฑธ ๋ฐฐ์› ๋‹ค.

 

* 2๊ฐœ ์ด์ƒ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์•  -> ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ „๋‹ฌ, 

* 2๊ฐœ ์ด์ƒ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์•  <- ์™ผ์ชฝ์œผ๋กœ ์ „๋‹ฌ

 

์ด ๋‘๊ฐ€์ง€๊ฐ€ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋ฉด ๋‹ค๋ฅธ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค๊ธฐ ๋•Œ๋ฌธ์— ์ˆœ์„œ๋ฅผ ๋ฐ”๊พผ ๊ฒฐ๊ณผ์˜ ์ˆ˜๋ฅผ ๋น„๊ตํ•ด์„œ ๊ฒฐ๊ณผ๋ฅผ ๋„์ถœํ–ˆ๋‹ค. 

 

function solution(n, lost, reserve) {
    const swts = Array.from({ length: n }, (v, i) => lost.includes(i + 1) ? 0 : 1).map((v, i) => reserve.includes(i + 1) ? v += 1 : v)
    const upper = (swts) => {
        for (let i = 0; i < swts.length; i++) {
            if (swts[i] === 0&& swts[i + 1] > 1) {
                    swts[i] += 1;
                    swts[i + 1] -= 1;
            }
        }
        return swts;
    }
    const lower = (swts) => {
        for (let i = 1; i < swts.length; i++) {
            if (swts[i] === 0&&swts[i - 1] > 1) {
                    swts[i] += 1;
                    swts[i - 1] -= 1;
            }
        }
        return swts;
    }
    const upperNumber = (swts) => lower(upper(swts)).filter(v => v !== 0).length;
    const lowerNumber = (swts) => upper(lower(swts)).filter(v => v !== 0).length;
    return Math.max(upperNumber([...swts]), lowerNumber([...swts]))
}

 

 

์˜ค๋Š˜๋„ ๋น„๋‚œ์ขŒ๊ฐ€ ๋„์™€์ฃผ์…จ๋‹ค. ํ–…์‚

 

 

function solution(n, lost, reserve) {
    let students = Array(n).fill(1);
    // ์ฒด์œก๋ณต์„ ์žƒ์–ด๋ฒ„๋ฆฐ ํ•™์ƒ ์ฒ˜๋ฆฌ
    lost.forEach(v => students[v-1]--);
    // ์—ฌ๋ฒŒ ์ฒด์œก๋ณต์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ํ•™์ƒ ์ฒ˜๋ฆฌ
    reserve.forEach(v => students[v-1]++);
    
    students.forEach((v, i) => {
        // ์ด ํ•™์ƒ์˜ ๋ฐ”๋กœ ์•ž์— ์—ฌ๋ณ„์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ง„ ํ•™์ƒ์ด ์žˆ์œผ๋ฉด ์„ธ๋น„์ง€ ํ•ฉ๋‹ˆ๋‹ค.
        if (!v && students[i-1] === 2) {
            students[i-1]--;
            students[i]++;
        }
        else if (!v && students[i+1] === 2) {
         // ์ด ํ•™์ƒ์˜ ๋ฐ”๋กœ ๋’ค์— ์—ฌ๋ณ„์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ง„ ํ•™์ƒ์ด ์žˆ์œผ๋ฉด ์„ธ๋น„์ง€ ํ•ฉ๋‹ˆ๋‹ค.
            students[i+1]--;
            students[i]++;
        }
    });

    return students.filter(v => v > 0).length;
}

 

 

 

๋น„๋‚œ๋‹˜ ๋‡Œ ์ƒˆ๋น„์ง€ ํ•˜๊ณ  ์‹ถ๋‹ค...

 

728x90
๋ฐ˜์‘ํ˜•