#2025

Maximum Number of Ways to Partition an Array

Hard
ArrayHash TableCountingEnumerationPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses prefix sums and a HashMap to efficiently count valid partitions without recalculating sums repeatedly. This reduces the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the total sum of the array and initialize a prefix sum and a HashMap to count occurrences of prefix sums.
  2. 2Step 2: Iterate through the array to fill the prefix sum and check for valid pivots.
  3. 3Step 3: For each index, calculate the required suffix sum and check if it exists in the HashMap.
  4. 4Step 4: For each element, consider changing it to k and adjust the prefix sum accordingly, checking for new valid partitions.
  5. 5Step 5: Return the maximum count of valid partitions found.
solution.py30 lines
1def maxWays(nums, k):
2    n = len(nums)
3    total_sum = sum(nums)
4    prefix_sum = 0
5    count = 0
6    prefix_count = {}
7
8    for i in range(n - 1):
9        prefix_sum += nums[i]
10        suffix_sum = total_sum - prefix_sum
11        if prefix_sum == suffix_sum:
12            count += 1
13        prefix_count[prefix_sum] = prefix_count.get(prefix_sum, 0) + 1
14
15    max_count = count
16
17    for i in range(n):
18        original = nums[i]
19        nums[i] = k
20        prefix_sum = 0
21        count = 0
22        for j in range(n - 1):
23            prefix_sum += nums[j]
24            suffix_sum = total_sum - prefix_sum
25            if prefix_sum == suffix_sum:
26                count += 1
27        max_count = max(max_count, count)
28        nums[i] = original
29
30    return max_count

Complexity note: The time complexity is O(n) due to a single pass through the array to calculate prefix sums and check for valid partitions. The space complexity is O(n) for storing prefix sums in the HashMap.

  • 1Changing one element can significantly affect the partitioning possibilities.
  • 2Using prefix sums allows for efficient calculation of partition conditions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.