Number of Ways to Split Array

medium array prefix sum

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].

Inputnums = [10, 4, -8, 7]
Output2
Splits at i=0 and i=2 satisfy left ≥ right.

def 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;
}
Time: O(n) Space: O(1)