Leetcode 3432. Count Partitions with Even Sum Difference

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
相关推荐
2501_94542354几秒前
C++编译期多态实现
开发语言·c++·算法
2401_87969387几秒前
设计模式在C++中的实现
开发语言·c++·算法
☆5664 分钟前
C++中的代理模式高级应用
开发语言·c++·算法
2301_818419015 分钟前
编译器命令选项优化
开发语言·c++·算法
m0_518019485 分钟前
C++图形编程(OpenGL)
开发语言·c++·算法
Jasmine_llq6 分钟前
《B4354 [GESP202506 一级] 假期阅读》
数据结构·算法·最值筛选算法(核心逻辑)·三元运算符简化分支算法·多输入顺序处理算法·整数算术运算算法·格式化输出算法
2301_8166512210 分钟前
自定义异常类设计
开发语言·c++·算法
weixin_4219226910 分钟前
C++与自动驾驶系统
开发语言·c++·算法
算法鑫探14 分钟前
C语言结构体:学生信息统计实战
c语言·数据结构·算法·新人首发
2501_9454248020 分钟前
高性能计算资源调度
开发语言·c++·算法