[LeetCode] Number of Ways to Split Array

2270. Number of Ways to Split Array

You are given a 0-indexed integer array nums of length n.

nums contains a valid split at index i if the following are true:

  • The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.
  • There is at least one element to the right of i. That is, 0 <= i < n - 1.

Return the number of valid splits in nums.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int waysToSplitArray(vector<int>& nums) {
long long l = 0, r = accumulate(begin(nums), end(nums), 0ll);
int res = 0;
for(int i = 0; i < nums.size() - 1; i++) {
l += nums[i];
r -= nums[i];
if(l >= r) res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/LeetCode/number-of-ways-to-split-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.