Capacity To Ship Packages Within D Days LeetCode solution in JavaScript
1/**2* @param {number[]} weights3* @param {number} days4* @return {number}5*/6var shipWithinDays = function (weights, days) {7// set left as max of weight, set right as sum of weight8let left = Math.max(...weights),9right = weights.reduce((a, b) => a + b);1011// max weight cannot exceed the capacity of ship12while (left < right) {13// set middle weight14const m = Math.floor((left + right) / 2);15// reset weight if can be load16can(m) ? (left = m + 1) : (right = m);17}1819// result20return left;2122// check if load can be23function can(v) {24let need = 1,25current = 0;2627for (let i of weights) {28if (current + i > v) {29need++;30current = i;31} else {32current += i;33}34}3536return need > days;37}38};