Prefix Sum VII

Very easy problem which could have been solved in N^2 since N = 100, but you can also use Prefix Sum technique here, which beats 100% in speed and memory. Code is down below, cheers, ACC.

Count Partitions with Even Sum Difference - LeetCode

You are given an integer array nums of length n.

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.

 

Example 1:

Input: nums = [10,10,3,7,6]

Output: 4

Explanation:

The 4 partitions are:

  • [10][10, 3, 7, 6] with a sum difference of 10 - 26 = -16, which is even.
  • [10, 10][3, 7, 6] with a sum difference of 20 - 16 = 4, which is even.
  • [10, 10, 3][7, 6] with a sum difference of 23 - 13 = 10, which is even.
  • [10, 10, 3, 7][6] with a sum difference of 30 - 6 = 24, which is even.

Example 2:

Input: nums = [1,2,2]

Output: 0

Explanation:

No partition results in an even sum difference.

Example 3:

Input: nums = [2,4,6,8]

Output: 3

Explanation:

All partitions result in an even sum difference.

 

Constraints:

  • 2 <= n == nums.length <= 100
  • 1 <= nums[i] <= 100

public int CountPartitions(int[] nums)
{
    int[] prefixSum = new int[nums.Length];

    prefixSum[0] = nums[0];
    for (int i = 1; i < nums.Length; i++)
        prefixSum[i] = nums[i] + prefixSum[i - 1];

    int retVal = 0;
    for (int i = 0; i < prefixSum.Length - 1; i++)
    {
        int left = prefixSum[i];
        int right = prefixSum[prefixSum.Length - 1] - prefixSum[i + 1] + nums[i + 1];
        if (Math.Abs(left - right) % 2 == 0)
            retVal++;
    }

    return retVal;
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Advent of Code - Day 7, 2024: Backtracking and Eval

Golang vs. C#: performance characteristics (simple case study)