class Solution { public: int splitArray(vector<int>& nums, int m) { int _max = -1, _sum = 0; for (auto n : nums) { if (n > _max) _max = n; _sum += n; } int i = _max, j = _sum; while (i < j - 1) { int mid = i + (j - i) / 2; if (valid(nums, m, mid)) j = mid; else i = mid+1; } return valid(nums, m, i) ? i : j; } bool valid(vector<int>& nums, int m, int _sum) { for (int cur_sum = 0, i = 0; i < nums.size(); i++) { if (nums[i] > _sum) return false; if (cur_sum + nums[i] > _sum) { cur_sum = 0; m--; if (m == 0) return false; } cur_sum += nums[i]; } return true; } };