3269. Constructing Two Increasing Arrays π
Description
Given 2 integer arrays nums1
and nums2
consisting only of 0 and 1, your task is to calculate the minimum possible largest number in arrays nums1
and nums2
, after doing the following.
Replace every 0 with an even positive integer and every 1 with an odd positive integer. After replacement, both arrays should be increasing and each integer should be used at most once.
Return the minimum possible largest number after applying the changes.
Example 1:
Input: nums1 = [], nums2 = [1,0,1,1]
Output: 5
Explanation:
After replacing, nums1 = []
, and nums2 = [1, 2, 3, 5]
.
Example 2:
Input: nums1 = [0,1,0,1], nums2 = [1,0,0,1]
Output: 9
Explanation:
One way to replace, having 9 as the largest element is nums1 = [2, 3, 8, 9]
, and nums2 = [1, 4, 6, 7]
.
Example 3:
Input: nums1 = [0,1,0,0,1], nums2 = [0,0,0,1]
Output: 13
Explanation:
One way to replace, having 13 as the largest element is nums1 = [2, 3, 4, 6, 7]
, and nums2 = [8, 10, 12, 13]
.
Constraints:
0 <= nums1.length <= 1000
1 <= nums2.length <= 1000
nums1
andnums2
consist only of 0 and 1.
Solutions
Solution 1: Dynamic Programming
We define $f[i][j]$ to represent the minimum of the maximum values among the first $i$ elements of array $\textit{nums1}$ and the first $j$ elements of array $\textit{nums2}$. Initially, $f[i][j] = 0$, and the answer is $f[m][n]$, where $m$ and $n$ are the lengths of arrays $\textit{nums1}$ and $\textit{nums2}$, respectively.
If $j = 0$, then the value of $f[i][0]$ can only be derived from $f[i - 1][0]$, with the transition equation $f[i][0] = \textit{nxt}(f[i - 1][0], \textit{nums1}[i - 1])$, where $\textit{nxt}(x, y)$ represents the smallest integer greater than $x$ that has the same parity as $y$.
If $i = 0$, then the value of $f[0][j]$ can only be derived from $f[0][j - 1]$, with the transition equation $f[0][j] = \textit{nxt}(f[0][j - 1], \textit{nums2}[j - 1])$.
If $i > 0$ and $j > 0$, then the value of $f[i][j]$ can be derived from both $f[i - 1][j]$ and $f[i][j - 1]$, with the transition equation $f[i][j] = \min(\textit{nxt}(f[i - 1][j], \textit{nums1}[i - 1]), \textit{nxt}(f[i][j - 1], \textit{nums2}[j - 1]))$.
Finally, return $f[m][n]$.
The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of arrays $\textit{nums1}$ and $\textit{nums2}$, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
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 |
|
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 |
|