Iamtui1010

bai3captruong-leetcode.cpp

Sep 20th, 2022
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include<vector>
  2. #include<algorithm>
  3.  
  4. #define long long long
  5.  
  6. using namespace std;
  7.  
  8. long max(long a, long b)
  9. {
  10.     if (a > b)
  11.         return a;
  12.     return b;
  13. }
  14.  
  15. bool check(vector<int> a, long k, long m )
  16. {
  17.     long cnt = 1, s = 0;
  18.     for (auto i : a){
  19.         if (s+i <= m)
  20.             s +=i;
  21.         else{
  22.             cnt++;
  23.             s = i;
  24.         }
  25.         if (cnt > k)
  26.             return 0;
  27.     }
  28.     return 1;
  29. }
  30.  
  31. class Solution {
  32. public:
  33.     int shipWithinDays(vector<int>& a, int k) {
  34.         cin.tie(0)->sync_with_stdio(0);
  35.         long n = a.size(), rig = 0, lef = 0, res = 0;
  36.         for (auto i : a){
  37.             rig += i;
  38.             lef = max(lef, i);
  39.         }
  40.        
  41.         while (lef <= rig){
  42.         long mid = (lef+rig)/2;
  43.         if (check(a, k, mid))
  44.             res = mid, rig = mid-1;
  45.         else
  46.             lef = mid+1;
  47.     }
  48.        
  49.         return res;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment