Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
0 <= nums1.length <= 1000
1 <= nums2.length <= 1000
nums1
andnums2
consist only of 0 and 1.
Solution
Method 1 – Greedy Assignment with Set
Intuition
We need to assign even positive integers to 0s and odd positive integers to 1s in both arrays, such that both arrays are strictly increasing and each integer is used at most once. The goal is to minimize the largest number used. The greedy approach is to assign the smallest available even/odd numbers to each position, maintaining the increasing property.
Approach
- Count the number of 0s and 1s in both arrays.
- For each array, create a list of positions for 0s and 1s.
- Assign the smallest available even numbers to 0s and the smallest available odd numbers to 1s, ensuring the sequence is strictly increasing.
- Use a set to keep track of used numbers.
- The answer is the largest number assigned.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the total length of nums1 and nums2. Each element is processed once. - 🧺 Space complexity:
O(n)
, for the even/odd arrays.