Problem
You are given an integer array nums of length n.
A partition is defined as an index i where 0 <= i < n - 1, splitting the array into two non-empty subarrays such that:
- Left subarray contains indices [0, i].
- Right subarray contains indices [i + 1, n - 1].
Return the number of partitions where the difference between the sum of the left and right subarrays is even.
Algorithm
Translate into English: Given an array, compute all possible partitioning methods such that the difference between the sum of the left subarray and the sum of the right subarray is even. A partitioning method refers to dividing the array into non-empty left and right subarrays.
Code
python3
class Solution:
def countPartitions(self, nums: List[int]) -> int:
sum_n, len_n = sum(nums), len(nums)
l_v, r_v, cnts = 0, sum_n, 0
for i in range(len_n-1):
l_v += nums[i]
r_v -=nums[i]
if (l_v - r_v) % 2 == 0:
cnts += 1
return cnts