Skip to content

Latest commit

 

History

History
43 lines (38 loc) · 1.04 KB

2023-02-22.md

File metadata and controls

43 lines (38 loc) · 1.04 KB

题目

  1. Capacity To Ship Packages Within D Days

A conveyor belt has packages that must be shipped from one port to another within days days.

The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

思路

Binary Search

代码

// runtime 63.78% memory 21.8%
var shipWithinDays = function(weights, days) {
  let l = 0
  let r = 0
  for (const w of weights) {
    l = Math.max(l, w)
    r += w
  }
  while (l < r) {
    const m = Math.floor(l + (r - l) / 2)
    let acc = 0
    let par = 1
    for (const w of weights) {
      if (acc + w > m) {
        acc = w
        par += 1
      } else {
        acc += w
      }
    }
    if (par <= days) {
      r = m
    } else {
      l = m + 1
    }
  }
  return l
}