Problem Description
Given an integer array nums, count the valid ways to partition it into two non-empty parts such that the sum of the left part equals the sum of the right part. You may change at most one element in nums to a given value k (or leave the array unchanged) to maximize the number of such valid partitions.
Key Insights
- Use the prefix sum technique to quickly compute sums of subarrays.
- A valid pivot index exists when the prefix sum equals half of the total sum (which must then be even).
- Changing one element affects all prefix sums from that index onward by a fixed diff = k - original_value.
- Pre-calculate the valid partition count for the unchanged array.
- Evaluate the impact of modifying each index by adjusting the prefix sums and count pivots accordingly.
- Careful handling of indices is required: for pivots before the modified index, no adjustment is made; for pivots at or after the modified index, add the diff.
Space and Time Complexity
Time Complexity: O(n^2) in a naive evaluation per index, but can be optimized to O(n) with precomputation and hash maps. Space Complexity: O(n) due to usage of prefix sums and dictionaries.
Solution
We first compute the total sum of the array. If the total is even, we calculate prefix sums to count the valid partitions without modification (where prefix sum equals total/2). Then for each index, consider changing nums[i] to k. This change introduces a diff = k - nums[i] which affects all subsequent prefix sums. By separating the counting into two cases (pivots before i and pivots at or after i) and comparing their adjusted sums to the target (newTotal/2), we determine the number of valid partitions after the modification. Finally, we return the maximum count from either modifying one element or keeping the array unchanged.