๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 1011 - Capacity To Ship Packages Within D Days (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 1011๋ฒˆ

ํ’€์ด ๊ณผ์ •

ํ™”๋ฌผ๋“ค์˜ ๋ฌด๊ฒŒ weights ๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ D ์ผ์— ๋ชจ๋“  ํ™”๋ฌผ์„ ๋ฐฐ์†กํ•˜๊ธฐ ์œ„ํ•œ ํ™”๋ฌผ์„ ์˜ ์ตœ์†Œ ๋ฌด๊ฒŒ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์‚ฌ์‹ค ๋ฌธ์ œ ๋ถ„๋ฅ˜๋Š” ์ด๋ถ„ ํƒ์ƒ‰ ์œผ๋กœ ๋˜์–ด ์žˆ์ง€๋งŒ ์ž…๋ ฅ์˜ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ ค ํ–ˆ์„ ๋•Œ ์™„์ „ ํƒ์ƒ‰ ์œผ๋กœ๋„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•˜์Šต๋‹ˆ๋‹ค.
๊ทธ๋ž˜๋„ ์ด๋ถ„ ํƒ์ƒ‰ ์„ ํ™œ์šฉํ•ด๋ณด๋ฉด ํ™”๋ฌผ์„ ์˜ ์ตœ์†Œ ๋ฐ ์ตœ๋Œ€ ๋ฌด๊ฒŒ๋ฅผ ์ •ํ•˜๊ณ 
๋ชจ๋“  ํ™”๋ฌผ์„ ์šด๋ฐ˜ํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ตœ์†Œ ์ผ์ˆ˜๋ฅผ ๊ตฌํ•ด์„œ ๋น„๊ตํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

ํšŒ๋ฌผ์„ ์˜ ์ตœ์†Œ ๋ฌด๊ฒŒ๋Š” ๋ชจ๋“  ํ™”๋ฌผ ์ค‘ ๊ฐ€์žฅ ๋ฌด๊ฑฐ์šด ๊ฒƒ์ด๋ฉฐ
์ตœ๋Œ€ ๋ฌด๊ฒŒ๋Š” ๋ชจ๋“  ํ™”๋ฌผ์„ ํ•˜๋ฃจ๋งŒ์— ๋ฐฐ์†กํ•˜๊ธฐ ์œ„ํ•œ ๋ฌด๊ฒŒ(์ฆ‰, ๋ชจ๋“  ํ™”๋ฌผ ๋ฌด๊ฒŒ์˜ ํ•ฉ) ์ž…๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} weights
 * @param {number} D
 * @return {number}
 */
var shipWithinDays = function (weights, D) {
  let lo = Math.max(...weights);
  let hi = weights.reduce((acc, weight) => acc + weight);
  let answer = -1;

  while (lo <= hi) {
    const mid = parseInt((lo + hi) / 2);
    const day = getShippingDay(weights, mid);

    if (day <= D) {
      answer = mid;
      hi = mid - 1;
    } else {
      lo = mid + 1;
    }
  }

  return answer;
};

function getShippingDay(weights, capacity) {
  let day = 1;
  let acc = 0;

  for (const weight of weights) {
    if (acc + weight <= capacity) acc += weight;
    else {
      acc = weight;
      day++;
    }
  }

  return day;
}
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 112 - Path Sum (Easy)  (0) 2021.03.04
LeetCode 63 - Unique Paths II (Medium)  (0) 2021.03.04
LeetCode 881 - Boats to Save People (Medium)  (0) 2021.03.04
LeetCode 234 - Palindrome Linked List (Easy)  (0) 2021.03.04
LeetCode 309 - Best Time to Buy and Sell Stock with Cooldown (Medium)  (0) 2021.03.04

๐Ÿ’ฌ ๋Œ“๊ธ€