A split of an integer array is good if:
- The array is split into three non-empty contiguous subarrays - named
left,mid,rightrespectively from left to right. - The sum of the elements in
leftis less than or equal to the sum of the elements inmid, and the sum of the elements inmidis less than or equal to the sum of the elements inright.
Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,1,1] Output: 1 Explanation: The only good way to split nums is [1] [1] [1].
Example 2:
Input: nums = [1,2,2,2,5,0] Output: 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0]
Example 3:
Input: nums = [3,2,1] Output: 0 Explanation: There is no good way to split nums.
Constraints:
3 <= nums.length <= 1050 <= nums[i] <= 104
Related Topics:
Binary Search
Turn array A into its prefix sum array.
Let i be the last index of the left part. So A[i] is the sum of the left part.
Given i, the last index of the mid part is a range. Let it be [j, k).
When we increment i, j and k must be monotonically increasing.
To find j, we can increment j from i + 1 until mid >= left i.e. A[j] - A[i] >= A[i].
To find k, we can increment k from j until mid < right, i.e. A[N - 1] - A[k] < A[k] - A[i].
// OJ: https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int waysToSplit(vector<int>& A) {
long mod = 1e9+7, ans = 0;
for (int i = 1; i < A.size(); ++i) A[i] += A[i - 1];
long N = A.size(), i = 0, j = 0, k = 0;
for (; i < N; ++i) {
long left = A[i];
j = max(i + 1, j); // `j` is at least one greater than `i`.
while (j < N && A[j] - left < left) ++j; // find the smallest `j` that satisfies `mid >= left`
if (j >= N) break; // No room for `k`. Break
k = max(k, j);
while (k < N - 1 && A.back() - A[k] >= A[k] - A[i]) ++k;
ans = (ans + k - j) % mod;
}
return ans;
}
};// OJ: https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
int waysToSplit(vector<int>& A) {
long mod = 1e9 + 7, ans = 0, N = A.size();
for (int i = 1; i < N; ++i) A[i] += A[i - 1];
for (int i = 0; i < N; ++i) {
long left = A[i], other = A.back() - left;
int j = lower_bound(begin(A) + i + 1, end(A), 2 * left) - begin(A);
int k = upper_bound(begin(A) + j, end(A) - 1, left + other / 2) - begin(A);
ans = (ans + k - j) % mod;
}
return ans;
}
};