A valid split at index i means the sum of elements from 0 to i is at least as large as the sum from i+1 to the end. The straightforward approach is to compute both sums for every possible split point by iterating through the relevant portions of the array each time.
i from 0 to n - 2:leftSum by iterating from 0 to i.rightSum by iterating from i + 1 to n - 1.leftSum >= rightSum, increment res.class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
n = len(nums)
res = 0
for i in range(n - 1):
leftSum = 0
for j in range(i + 1):
leftSum += nums[j]
rightSum = 0
for j in range(i + 1, n):
rightSum += nums[j]
res += (1 if leftSum >= rightSum else 0)
return resRecomputing sums from scratch for each split is wasteful. By precomputing a prefix sum array, we can find the sum of any subarray in constant time. The left sum up to index i is prefix[i], and the right sum is prefix[n] - prefix[i].
prefix[i] is the sum of the first i elements.i from 1 to n - 1:left = prefix[i].right = prefix[n] - prefix[i].left >= right, increment res.class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
n = len(nums)
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + nums[i]
res = 0
for i in range(1, n):
left = prefix[i]
right = prefix[n] - prefix[i]
if left >= right:
res += 1
return resWe don't need to store the entire prefix sum array. Instead, we can maintain a running left sum and right sum. Start with right as the total, then shift elements from right to left as we iterate through possible split points.
right.left = 0 and res = 0.i from 0 to n - 2:nums[i] to left and subtract it from right.left >= right, increment res.res.