1712. Ways to Split Array Into Three Subarrays
SourceWeekly Contest 222 Q3DifficultyMediumRating2078
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 1: Prefix Sum + Binary Search
Thinking
We need three nonempty parts with \(s_{\textit{left}}\le s_{\textit{mid}}\le s_{\textit{right}}\). Two nested cuts are \(O(n^2)\) and fail for \(n\le 10^5\).
Values are nonnegative, so prefix sums are monotone. After fixing the left cut \(i\), the mid cut lies in a contiguous range and can be found by binary search.
The range is \(s[j]\ge 2s[i]\) and \(s[k]\le (s[-1]+s[i])/2\). Two binary searches per \(i\) count the ways, taken modulo \(10^9+7\).
First, we preprocess the prefix sum array \(s\) of the array \(nums\), where \(s[i]\) represents the sum of the first \(i+1\) elements of the array \(nums\).
Since all elements of the array \(nums\) are non-negative integers, the prefix sum array \(s\) is a monotonically increasing array.
We enumerate the index \(i\) that the left subarray can reach in the range \([0,..n-2)\), and then use the monotonically increasing characteristic of the prefix sum array to find the reasonable range of the mid subarray split by binary search, denoted as \([j, k)\), and accumulate the number of schemes \(k-j\).
In the binary search details, the subarray split must satisfy \(s[j] \geq s[i]\) and \(s[n - 1] - s[k] \geq s[k] - s[i]\). That is, \(s[j] \geq s[i]\) and \(s[k] \leq \frac{s[n - 1] + s[i]}{2}\).
Finally, return the number of schemes modulo \(10^9+7\).
The time complexity is \(O(n \times \log n)\), where \(n\) is the length of the array \(nums\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |