๐Ÿ’Ž

ARR PS - moving bricks

notion image
ย 
notion image
ย 

ํ’€์–ด๋ณด๊ธฐ

[5, 2, 4, 1, 7, 5]
4, 3, 4, 1, 7, 5
4, 4, 4, 1, 6, 5
4, 4, 4, 2, 5, 5
4, 4, 4, 3, 4, 5
4, 4, 4, 4, 4, 4
๋จผ์ € ๋†’์ด ๋ช‡์„ ๋งž์ถฐ์•ผ ํ•˜๋Š”์ง€ ๊ตฌํ•œ๋‹ค. โ‡’ ๋ฐฐ์—ด์˜ ์›์†Œ์˜ ์ดํ•ฉ : 24, ๋ฐฐ์—ด์˜ ๊ธธ์ด : 6, ๋‚˜๋ˆ„๋ฉด 4๊ฐ€ ๋œ๋‹ค.
ํ•œ๋ฒˆ ๋นผ๋ฉด ํ•œ๋ฒˆ ๋”ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. ์ด๊ฑธ ํ•˜๋‚˜์˜ ์›€์ง์ž„์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค.
๋งˆ์ง€๋ง‰์— ๋†’์ด๋กœ๋งŒ ๊ตฌ์„ฑ๋œ ๋ฐฐ์—ด์ธ์ง€ set์œผ๋กœ ํŒ๋‹จํ•ด์„œ while๋ฌธ์ด ์ข…๋ฃŒ๋˜๋„๋ก ํ–ˆ๋‹ค.
ย 
function answer(nums) {
    let move = 0;
    let height = nums.reduce((cur, acc) => cur + acc) / nums.length;
    while (true) {
        for (let i = 0; i < nums.length; i++) {
            if (height < nums[i]) {
                move++;
                nums[i]--;
            } else if (height === nums[i]) continue;
            else nums[i]++;
        }
        let set = new Set(nums);
        if (set.size === 1) break;
    }
    return move;
}