当前位置: 代码迷 >> 综合 >> leetcode 1014. Capacity To Ship Packages Within D Days
  详细解决方案

leetcode 1014. Capacity To Ship Packages Within D Days

热度:31   发布时间:2024-01-16 17:57:10.0

leetcode 1014. Capacity To Ship Packages Within D Days

题意:给你一个数组,表示一堆货的重量。再给你一个数d,表示要求运货的天数。求一个最小的载重量,满足d天内运完这些货。货必须按次序运。

思路:直接二分载重量,求个最小值就好了。

class Solution {
public:int shipWithinDays(vector<int>& weights, int D) {int l = 1;int r = INT_MAX;while (l <= r){int mid = l + (r - l) / 2;if (gao(mid, weights, D))r = mid-1;elsel = mid+1;}return l;}bool gao(int m, vector<int>& weights, int D){int now=0;for (int i = 1; i <= D; i++){int sum = 0;while (now < weights.size() && sum + weights[now] <= m)sum += weights[now++];if (now >= weights.size())return true;}return false;}
};

 

  相关解决方案