Advertisement
nikunjsoni

1011

May 14th, 2021
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shipWithinDays(vector<int>& weights, int D) {
  4.         // Sort the weights.
  5.         int r, l, ans;
  6.         r = accumulate(weights.begin(), weights.end(), 0);
  7.         l = max(r/D, *max_element(weights.begin(), weights.end()));
  8.                
  9.         while(l<=r){
  10.             int mid = (l+r)/2;
  11.             if(canShip(weights, mid, D)){
  12.                 ans = mid;
  13.                 r = mid-1;
  14.             }
  15.             else{
  16.                 l = mid+1;
  17.             }
  18.         }
  19.         return ans;
  20.     }
  21.    
  22.     bool canShip(vector<int>& weights, int cap, int d){
  23.         int days = 1, sum = 0;
  24.         for(auto &w: weights){
  25.             sum += w;
  26.             if(sum > cap){
  27.                 days++;
  28.                 sum = w;
  29.             }
  30.         }
  31.         return days <= d;
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement