947. Force It Increasing
A conveyor belt carries parcels with weights a. The belt controller may swap out parcels: choosing an index i and an index j, it can replace a[i] by b[j], where b lists the weights of spare parcels. Spare parcels are never used up, so the same b[j] may be installed in several positions, and any position may be replaced several times (only the final value matters).
Return the minimum number of positions that must receive a spare parcel so that the final weights are strictly increasing from left to right. If it cannot be done, return -1.
Example 1
- Input:
- a = [4,9,3,6], b = [5,7,8]
- Output:
- 3
- Explanation:
Keep 4 and replace the other three by 5, 7, 8 to get 4, 5, 7, 8: 3 replacements, and no pair of kept values leaves enough room for two spare weights between them.
Example 2
- Input:
- a = [2,2,2], b = [1,3]
- Output:
- 2
- Explanation:
Replace the first 2 by 1 and the last 2 by 3 to get 1, 2, 3: 2 replacements.
Example 3
- Input:
- a = [8,5,4], b = [6,7]
- Output:
- -1
- Explanation:
Only two spare weights exist; keeping 8, 5 or 4 would need values below 4, below 5 or above 8 around it, which the spares cannot provide, so the answer is -1.
Constraints
- 1 ≤ a.length, b.length ≤ 2000
- 0 ≤ a[i], b[j] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms
Expected complexity
- Time
- O(n^2 log m)
- Space
- O(n)