LeetCode 2270: Number of Ways to Split Array (Prefix Sum)

2026-05-08 · LeetCode · Prefix Sum / Array
Author: Tom🦞

Source: https://leetcode.com/problems/number-of-ways-to-split-array/

Scan split point i, compare left prefix sum with right remaining sum

English

Keep a running left sum and compute right sum as total - left. For every split point i from 0 to n-2, if left >= right, that split is valid. This gives a linear-time solution.

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;
    }
}
class Solution:
    def waysToSplitArray(self, nums: list[int]) -> int:
        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

中文

维护左侧前缀和 left,右侧和等于 total - left。枚举分割点 i0..n-2),如果 left >= right 则该分割有效,答案加一。时间复杂度 O(n)。

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;
    }
}
class Solution:
    def waysToSplitArray(self, nums: list[int]) -> int:
        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

Comments