The idea is the minimized maximum sum among the subarrays must between the largest number in the array and the sum of the total array. So we should think of the binary search.
Once we think about the binary search, we need to find the validation condition. Given the mid number, the condition is invalid if there are more than m subarrays that have sum larger than mid number.
1: class Solution {
2: public:
3: int splitArray(vector<int>& nums, int m) {
4: long long left = 0, right = 0;
5: for (n : nums) {
6: left = max(left, (long long)n);
7: right += n;
8: }
9: while (left < right) {
10: long long mid = (left + right) / 2;
11: if (isValid(nums, m, mid)) right = mid;
12: else left = mid + 1;
13: }
14: return left;
15: }
16: bool isValid(vector<int> &nums, int m, int maxSum) {
17: long long cur = 0;
18: int count = 0;
19: for (n : nums) {
20: cur += n;
21: if (cur > maxSum) {
22: cur = n, count++;
23: // you've got m subarrays that have sum larger than maxSum,
24: // so maxSum isn't a minimized sum among these subarrays.
25: if (count == m) return false;
26: }
27: }
28: return true;
29: }
30: };
No comments:
Post a Comment