Skip to content

2270. Number of Ways to Split Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int waysToSplitArray(vector<int>& nums) {
    int ans = 0;
    long prefix = 0;
    long suffix = accumulate(nums.begin(), nums.end(), 0L);

    for (int i = 0; i < nums.size() - 1; ++i) {
      prefix += nums[i];
      suffix -= nums[i];
      if (prefix >= suffix)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int waysToSplitArray(int[] nums) {
    int ans = 0;
    long prefix = 0;
    long suffix = Arrays.stream(nums).asLongStream().sum();

    for (int i = 0; i < nums.length - 1; ++i) {
      prefix += nums[i];
      suffix -= nums[i];
      if (prefix >= suffix)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def waysToSplitArray(self, nums: list[int]) -> int:
    ans = 0
    prefix = 0
    suffix = sum(nums)

    for i in range(len(nums) - 1):
      prefix += nums[i]
      suffix -= nums[i]
      if prefix >= suffix:
        ans += 1

    return ans