Replace Sort
InterviewTime limit3sMemory limit1024 MB
Given an array A and a set B of distinct values, find the fewest elements of A to replace with values from B so that A becomes sorted, or report -1.
- Level
Medium6 of 10
- Topics
- Greedy, Sorting, Binary search, Array
- Solved
- No attempts yet
Problem
Consider an array and a set of integers such that all numbers in and are distinct. Your task is to turn into a sorted array. To do this, you can take any number from and replace any element of with it. You can perform this operation any number of times, but each element of can be used at most once.
Determine the minimum number of operations needed to turn into a sorted array, or determine that it is impossible.
Input
The first line of input contains two integers and (), the sizes of and .
The second line contains integers .
The third line contains integers .
All the elements are distinct, positive, and do not exceed .
Output
If it is impossible to turn into a sorted array, print . Otherwise, print the minimum number of operations needed.
Hint
In all three examples, the issue is that , so at least one of them must be changed.
In the first one, we can decrease by replacing it with , but that breaks the other side, so there is no solution.
In the second one, can fix the broken side. It is impossible to do it with fewer than operations.
In the third example, we can increase the last element, which fixes in 1 operation.