Approach¶
-
Prefix and suffix sums:
-
Use a prefix sum array to calculate the sum of the first
i + 1elements. -
Use the total sum of the array to calculate the suffix sum dynamically: $suffixSum = totalSum - prefixSum$.
-
Check valid Splits:
-
Iterate through the array from index
0ton-2. -
For each i, check if: $$prefixSum \ge suffixSum$$ equivalent to: $$2 * prefixSum \ge totalSum$$
-
Count valid Splits:
-
Increment the count whenever the above condition is true.
Complexity¶
-
Time complexity:
O(N)where N is the length of the given array. -
Space complexity:
O(1)extra space.
Code¶
Go¶
func waysToSplitArray(nums []int) int {
ans, n, totalSum := 0, len(nums), 0
for _, num := range nums {
totalSum += num
}
sum := 0
for i := 0; i < n - 1; i++ {
sum += nums[i]
if 2 * sum >= totalSum {
ans++
}
}
return ans
}