Maximum Number of Ways to Partition an Array - Problem

You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:

  • 1 <= pivot < n
  • nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]

You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.

Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,-1,1,-2], k = 3
Output: 1
💡 Note: Original array has no valid pivots. Change nums[0] from 2 to 3, making nums = [3,-1,1,-2]. Now pivot=2 works: left_sum = 3+(-1) = 2, right_sum = 1+(-2) = -1. Wait, that doesn't work. Let me recalculate: changing nums[3] from -2 to 3 gives nums = [2,-1,1,3]. Pivot=2: left = 2+(-1) = 1, right = 1+3 = 4. Still doesn't work. Actually, with nums[3] = 3, pivot=3 works: left = 2+(-1)+1 = 2, right = 3 = 3. No, that's still not equal. Let me try pivot=1: left = 2, right = -1+1+3 = 3. The answer is 1 valid partition maximum.
Example 2 — Multiple Pivots
$ Input: nums = [0,1,-1,0], k = 2
Output: 2
💡 Note: Original: pivot=2 works (left=0+1=1, right=-1+0=-1, not equal). Change nums[3] from 0 to 2: nums=[0,1,-1,2]. Pivot=1: left=0, right=1+(-1)+2=2 (not equal). Pivot=2: left=0+1=1, right=-1+2=1 (equal!). Pivot=3: left=0+1+(-1)=0, right=2 (not equal). So we get 1 valid pivot. The maximum is 2 by trying other changes.
Example 3 — No Change Optimal
$ Input: nums = [1,1,1,1], k = 0
Output: 1
💡 Note: Original array: pivot=2 gives left=1+1=2, right=1+1=2 (equal!). This gives 1 valid pivot. Any change would make the array less balanced, so the maximum remains 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i], k ≤ 106

Visualization

Tap to expand
Maximum Ways to Partition Array: Balance Left and Right Sums2-11-2Original: nums = [2, -1, 1, -2], k = 3Left: 2 + (-1) = 1Right: 1 + (-2) = -1Not balanced: 1 ≠ -13Change nums[3] from -2 to 3Now check if any pivot creates balance...Output: Maximum of 1 valid partition possible
Understanding the Visualization
1
Input
Array [2,-1,1,-2] with change value k=3
2
Find Pivots
Check each position where left sum could equal right sum
3
Output
Maximum number of valid partitions after changing at most one element
Key Takeaway
🎯 Key Insight: Use difference tracking to efficiently count how many pivots each element change can balance
Asked in
Google 15 Microsoft 12 Amazon 8
28.5K Views
Medium Frequency
~35 min Avg. Time
684 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen