[LeetCode] Ways to Split Array Into Three Subarrays

1712. Ways to Split Array Into Three Subarrays

A split of an integer array is good if:

  • The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.
  • The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int waysToSplit(vector<int>& nums) {
long res = 0;
partial_sum(begin(nums), end(nums), begin(nums));
for(auto left = 0, midBegin = 0, midEnd = 0; left < nums.size() - 2 && nums[left] * 3 <= nums.back(); ++left) {
while(midBegin <= left || (midBegin < nums.size() - 1 && nums[left]<<1 > nums[midBegin])) ++midBegin;
while(midBegin > midEnd || (midEnd < nums.size() - 1 && nums[midEnd]<<1 <= nums.back() + nums[left])) ++midEnd;
res += midEnd - midBegin;
}
return res % 1000000007;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/30/PS/LeetCode/ways-to-split-array-into-three-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.