Number of Ways to Split Array
Problem
Return the number of valid split indices i (0 ≤ i < n−1) where the sum of nums[0..i] is at least the sum of nums[i+1..n−1].
nums = [10, 4, -8, 7]2def ways_to_split_array(nums):
total = sum(nums)
left = 0
ans = 0
for i in range(len(nums) - 1):
left += nums[i]
if left >= total - left:
ans += 1
return ans
function waysToSplitArray(nums) {
let total = 0;
for (const x of nums) total += x;
let left = 0, ans = 0;
for (let i = 0; i < nums.length - 1; i++) {
left += nums[i];
if (left >= total - left) ans++;
}
return ans;
}
class Solution {
public int waysToSplitArray(int[] nums) {
long total = 0;
for (int x : nums) total += x;
long left = 0;
int ans = 0;
for (int i = 0; i < nums.length - 1; i++) {
left += nums[i];
if (left >= total - left) ans++;
}
return ans;
}
}
int waysToSplitArray(vector<int>& nums) {
long long total = 0;
for (int x : nums) total += x;
long long left = 0;
int ans = 0;
for (int i = 0; i < (int)nums.size() - 1; i++) {
left += nums[i];
if (left >= total - left) ans++;
}
return ans;
}
Explanation
We want to count split points where the left part's sum is at least the right part's sum. The trick is that once we know the total of the whole array, the right part is never computed directly — it is just total - left.
So we add up everything once to get total, then sweep i from the start to the second-to-last index, growing a running prefix sum left as we go.
At each split we simply check left >= total - left. If it holds, that split is valid and we add one to the count. Because both sides come from the same running total, every check is constant time.
Example: nums = [10, 4, -8, 7] has total 13. At i = 0, left 10 vs right 3 — valid. At i = 2, left 6 vs right 7 — not valid... actually left is 10+4-8 = 6 and right is 7, so it fails; the valid splits are at i = 0 and i = 1, giving the answer 2.