1712. Ways to Split Array Into Three Subarrays
Description
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
Solutions
Solution: Prefix Sum + Two Pointers
- Time complexity: O(n)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[]} nums
* @return {number}
*/
const waysToSplit = function (nums) {
const MODULO = 10 ** 9 + 7;
const prefixSum = [nums[0]];
const size = nums.length;
let mid = 0;
let right = 0;
let result = 0;
for (let index = 1; index < size; index++) {
prefixSum[index] = prefixSum[index - 1] + nums[index];
}
for (let index = 0; index < size - 2; index++) {
const current = prefixSum[index];
mid = Math.max(index + 1, mid);
while (mid < size - 1 && prefixSum[mid] - current < current) mid += 1;
right = Math.max(mid, right);
while (right < size - 1 && prefixSum[right] - current <= prefixSum.at(-1) - prefixSum[right]) {
right += 1;
}
result += right - mid;
result %= MODULO;
}
return result;
};