3599. Partition Array to Minimize XOR
Description
You are given an integer array nums
and an integer k
.
Your task is to partition nums
into k
non-empty subarrays. For each subarray, compute the bitwise XOR of all its elements.
Return the minimum possible value of the maximum XOR among these k
subarrays.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 1
Explanation:
The optimal partition is [1]
and [2, 3]
.
- XOR of the first subarray is
1
. - XOR of the second subarray is
2 XOR 3 = 1
.
The maximum XOR among the subarrays is 1, which is the minimum possible.
Example 2:
Input: nums = [2,3,3,2], k = 3
Output: 2
Explanation:
The optimal partition is [2]
, [3, 3]
, and [2]
.
- XOR of the first subarray is
2
. - XOR of the second subarray is
3 XOR 3 = 0
. - XOR of the third subarray is
2
.
The maximum XOR among the subarrays is 2, which is the minimum possible.
Example 3:
Input: nums = [1,1,2,3,1], k = 2
Output: 0
Explanation:
The optimal partition is [1, 1]
and [2, 3, 1]
.
- XOR of the first subarray is
1 XOR 1 = 0
. - XOR of the second subarray is
2 XOR 3 XOR 1 = 0
.
The maximum XOR among the subarrays is 0, which is the minimum possible.
Constraints:
1 <= nums.length <= 250
1 <= nums[i] <= 109
1 <= k <= n
Solutions
Solution 1: Dynamic Programming
We define \(f[i][j]\) as the minimum possible value of the maximum XOR among all ways to partition the first \(i\) elements into \(j\) subarrays. Initially, set \(f[0][0] = 0\), and all other \(f[i][j] = +\infty\).
To quickly compute the XOR of a subarray, we can use a prefix XOR array \(g\), where \(g[i]\) represents the XOR of the first \(i\) elements. For the subarray \([h + 1...i]\) (with indices starting from \(1\)), its XOR value is \(g[i] \oplus g[h]\).
Next, we iterate \(i\) from \(1\) to \(n\), \(j\) from \(1\) to \(\min(i, k)\), and \(h\) from \(j - 1\) to \(i - 1\), where \(h\) represents the end position of the previous subarray (indices starting from \(1\)). We update \(f[i][j]\) using the following state transition equation:
Finally, we return \(f[n][k]\), which is the minimum possible value of the maximum XOR when partitioning the entire array into \(k\) subarrays.
The time complexity is \(O(n^2 \times k)\), and the space complexity is \(O(n \times k)\), where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|