nikunjsoni

410

May 11th, 2021
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int splitArray(vector<int>& nums, int m) {
  4.         int low, high, sum;
  5.         sum = low = 0;
  6.         for(auto &num : nums){
  7.             sum += num;
  8.             low = max(low, num);
  9.         }
  10.         high = sum;
  11.        
  12.         while(low < high){
  13.             int mid = (low+high+1)/2;
  14.             int cuts = 0;
  15.             sum = 0;
  16.             for(auto &num : nums){
  17.                 sum += num;
  18.                 if(sum >= mid){
  19.                     sum = num;
  20.                     cuts++;
  21.                 }
  22.                 if(cuts == m) break;
  23.             }
  24.            
  25.             if(cuts < m)
  26.                 high = mid-1;
  27.             else
  28.                 low = mid;
  29.         }
  30.         return low;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment