Constructing Two Increasing Arrays Problem
Description
LeetCode Problem 3269.
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 <= 10001 <= nums2.length <= 1000nums1andnums2consist only of 0 and 1.
Solution
Approach: Dynamic Programming
Let f[i][j] be the smallest possible maximum after placing the first i elements of nums1 and the first j elements of nums2. Define nxt(x, y) as the smallest integer greater than x with the same parity as y (x + 1 or x + 2).
f[i][0] = nxt(f[i-1][0], nums1[i-1])andf[0][j] = nxt(f[0][j-1], nums2[j-1]).- Otherwise the last placed number comes from either array:
f[i][j] = min(nxt(f[i-1][j], nums1[i-1]), nxt(f[i][j-1], nums2[j-1])).
The answer is f[m][n].
Complexity: O(mn) time and O(mn) space.
class Solution:
def minLargest(self, nums1: List[int], nums2: List[int]) -> int:
def nxt(x: int, y: int) -> int:
return x + 1 if (x & 1 ^ y) == 1 else x + 2
m, n = len(nums1), len(nums2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i, x in enumerate(nums1, 1):
f[i][0] = nxt(f[i - 1][0], x)
for j, y in enumerate(nums2, 1):
f[0][j] = nxt(f[0][j - 1], y)
for i, x in enumerate(nums1, 1):
for j, y in enumerate(nums2, 1):
f[i][j] = min(nxt(f[i - 1][j], x), nxt(f[i][j - 1], y))
return f[m][n]