leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0410.cpp (830B)


      1 class Solution {
      2     int res = INT_MAX;
      3 
      4     bool doable(const vector<int> &nums, int cuts, long long maxi) {
      5         long long acc = 0;
      6 
      7         for (const int num : nums) {
      8             if (acc + num <= maxi)
      9                 acc += num;
     10             else {
     11                 if (--cuts < 0) return false;
     12                 acc = num;
     13             }
     14         }
     15 
     16         return true;
     17     }
     18 
     19   public:
     20     int splitArray(const vector<int> &nums, int k) {
     21         long long low = 0, high = 0;
     22 
     23         for (const long long n : nums) {
     24             low = max(low, n);
     25             high += n;
     26         }
     27 
     28         while (low < high) {
     29             const auto mid = low + (high - low) / 2;
     30             if (doable(nums, k - 1, mid))
     31                 high = mid;
     32             else
     33                 low = mid + 1;
     34         }
     35 
     36         return low;
     37     }
     38 };