์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜7] ๋ฎค์ง๋น„๋””์˜ค (Javascript)

์€์ง„ 2021. 6. 27. 23:54

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜7] ๋ฎค์ง๋น„๋””์˜ค (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-27

1. ๋ฌธ์ œ ์ดํ•ด

  • ์ˆœ์„œ ๊ทธ๋Œ€๋กœ ์œ ์ง€
  • DVD ์šฉ๋Ÿ‰ ์ตœ์†Œํ™”

2. DVD ๊ฐœ์ˆ˜์™€ ์ƒ๊ด€์—†์ด DVD๊ฐ€ ๊ผญ ๋‹ด์•„์•ผํ•  ์šฉ๋Ÿ‰

  • ์ตœ์†Œ์šฉ๋Ÿ‰ : 9
  • ์ตœ๋Œ€์šฉ๋Ÿ‰ : 1+2+โ€ฆ+9 = 45

3. ์ด๋ถ„๊ฒ€์ƒ‰ ๊ตฌํ˜„

  • left = 9, right = 45
  • while (left <= right)
  • left = mid+1; right = mid-1;

4. DVD์šฉ๋Ÿ‰์ด mid์ผ ๋•Œ, DVD ๋ช‡ ๊ฐœ๊ฐ€ ํ•„์š”ํ•œ์ง€ ํ™•์ธ

function count (mid, arr) {
  let cnt = 1;
  let sum = 0;

  for (let i=arr.length-1; i>=0; i--) {
    sum += arr[i];
    if (sum > mid) {
      cnt++;
      sum = arr[i]
    }
  }
  return cnt;
}


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-27

function count (mid, arr) {
  let cnt = 1;
  let sum = 0;

  for (let i=arr.length-1; i>=0; i--) {
    sum += arr[i];
    if (sum > mid) {
      cnt++;
      sum = arr[i]
    }
  }
  return cnt;
}

function solution(m, arr) {
  let left = arr[arr.length - 1], right = 0;
  for (let x of arr) right += x;  
  arr.sort((a, b) => a-b);

  while (left <= right) {
    let mid = Math.floor((right + left)/ 2);
    let cnt = count(mid, arr);

    if (cnt === m) return mid;
    else if (cnt < m) right = mid-1;  // ์ €์žฅ์šฉ๋ž‘์ด ํฌ๋‹ค
    else if (cnt > m) left = mid+1;  // ์ €์žฅ์šฉ๋Ÿ‰์ด ๋ถ€์กฑํ•˜๋‹ค
  }
}


โœ๏ธ๋†“์นœ ๊ฒƒ 2๊ฐ€์ง€

1. arr.sort()ํ•  ํ•„์š” ์—†๋‹ค

  • let left = Math.max(โ€ฆarr);
  • let right = arr.reduce((a, b) => a+b, 0);

2. if (count(mid, arr) === m) return mid; ์—์„œ ์ƒ๊ธฐ๋Š” ๋ฌธ์ œ

  • mid-1, mid-2, โ€ฆ ์˜ ์šฉ๋Ÿ‰์œผ๋กœ๋„ ๋ฌธ์ œ์กฐ๊ฑด์„ ๋งŒ์กฑํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ๋”ฐ๋ผ์„œ if (count(mid, arr) === m) ์ผ ๋•Œ ๋ฌด์กฐ๊ฑด ์—ฐ์‚ฐ์„ ์ข…๋ฃŒํ•˜๋ฉด ์•ˆ๋œ๋‹ค.
if (count(mid, arr) <= m) right = mid-1;