LeetCode Entry
3432. Count Partitions with Even Sum Difference
Count Left sum - Right sum % 2
3432. Count Partitions with Even Sum Difference easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1194
Problem TLDR
Count Left sum - Right sum % 2 #easy
Intuition
Just brute-force.
Approach
- a more interesting solution: A-B %2 == 0 only if both odd or both even.
- step i+0, […….even_sum][……….even_sum]
- step i+1, […….even_sum,odd][……….even_sum-odd]
- step i+1, […….even_sum,even][……….even_sum-even]
- basically, the even-ness will be the same for every partition
- same proof for odd-ness
Complexity
-
Time complexity: \(O(n^2)\), or O(n) for clever solution
-
Space complexity: \(O(1)\)
Code
// 11ms
fun countPartitions(n: IntArray) =
(n.size-1)* (1-n.sum()%2)
// 0ms
pub fn count_partitions(n: Vec<i32>) -> i32 {
(n.len()as i32-1)*(1-n.iter().sum::<i32>()%2)
}