LeetCode-in-Java

2270. Number of Ways to Split Array

Medium

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:

Return the number of valid splits in nums.

Example 1:

Input: nums = [10,4,-8,7]

Output: 2

Explanation: There are three ways of splitting nums into two non-empty parts:

Example 2:

Input: nums = [2,3,1,0]

Output: 2

Explanation: There are two valid splits in nums:

Constraints:

Solution

public class Solution {
    public int waysToSplitArray(int[] nums) {
        long leftSum = 0;
        long rightSum = 0;
        for (int i : nums) {
            rightSum += i;
        }
        int count = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            rightSum -= nums[i];
            leftSum += nums[i];
            if (leftSum >= rightSum) {
                count++;
            }
        }
        return count;
    }
}