Maximum Number of Ways to Partition an Array — LeetCode 2025 Python Solution
- Problem
- #2025
- Pattern
- Prefix Sum
- Reading time
- 4 min
- Source
- leetcode.com
The 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] + ...
Example
- Input
- nums = [2,-1,2], k = 3
- Output
- 1
- Explanation
- One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].
Python solution
class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
n = len(nums)
s = [nums[0]] * n
right = defaultdict(int)
for i in range(1, n):
s[i] = s[i - 1] + nums[i]
right[s[i - 1]] += 1
ans = 0
if s[-1] % 2 == 0:
ans = right[s[-1] // 2]
left = defaultdict(int)
for v, x in zip(s, nums):
d = k - x
if (s[-1] + d) % 2 == 0:
t = left[(s[-1] + d) // 2] + right[(s[-1] - d) // 2]
if ans < t:
ans = t
left[v] += 1
right[v] -= 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2025. Maximum Number of Ways to Partition an Array is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2025. Maximum Number of Ways to Partition an Array?
- LeetCode 2025. Maximum Number of Ways to Partition an Array is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2025. Maximum Number of Ways to Partition an Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2025. Maximum Number of Ways to Partition an Array?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2025. Maximum Number of Ways to Partition an Array cover?
- LeetCode 2025. Maximum Number of Ways to Partition an Array is tagged Array, Hash Table, Counting, Enumeration and Prefix Sum on LeetCode.