Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int shipWithinDays(vector<int>& weights, int D) {
- // Sort the weights.
- int r, l, ans;
- r = accumulate(weights.begin(), weights.end(), 0);
- l = max(r/D, *max_element(weights.begin(), weights.end()));
- while(l<=r){
- int mid = (l+r)/2;
- if(canShip(weights, mid, D)){
- ans = mid;
- r = mid-1;
- }
- else{
- l = mid+1;
- }
- }
- return ans;
- }
- bool canShip(vector<int>& weights, int cap, int d){
- int days = 1, sum = 0;
- for(auto &w: weights){
- sum += w;
- if(sum > cap){
- days++;
- sum = w;
- }
- }
- return days <= d;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement