Class Solution
- java.lang.Object
-
- g2601_2700.s2612_minimum_reverse_operations.Solution
-
public class Solution extends Object
2612 - Minimum Reverse Operations.Hard
You are given an integer
nand an integerpin the range[0, n - 1]. Representing a 0-indexed arrayarrof lengthnwhere all positions are set to0’s, except positionpwhich is set to1.You are also given an integer array
bannedcontaining some positions from the array. For the ith position inbanned,arr[banned[i]] = 0, andbanned[i] != p.You can perform multiple operations on
arr. In an operation, you can choose a subarray with sizekand reverse the subarray. However, the1inarrshould never go to any of the positions inbanned. In other words, after each operationarr[banned[i]]remains0.Return an array
answhere for eachifrom[0, n - 1],ans[i]is the minimum number of reverse operations needed to bring the1to positioniin arr, or-1if it is impossible.- A subarray is a contiguous non-empty sequence of elements within an array.
- The values of
ans[i]are independent for alli’s. - The reverse of an array is an array containing the values in reverse order.
Example 1:
Input: n = 4, p = 0, banned = [1,2], k = 4
Output: [0,-1,-1,1]
Explanation:
In this case
k = 4so there is only one possible reverse operation we can perform, which is reversing the whole array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is0. We can never place a 1 on the banned positions, so the answer for positions 1 and 2 is-1. Finally, with one reverse operation we can bring the 1 to index 3, so the answer for position 3 is1.Example 2:
Input: n = 5, p = 0, banned = [2,4], k = 3
Output: [0,-1,-1,-1,-1]
Explanation:
In this case the 1 is initially at position 0, so the answer for that position is
0. We can perform reverse operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray[0, 2]for it to leave that position, but reversing that subarray makes position 2 have a 1, which shouldn’t happen. So, we can’t move the 1 from position 0, making the result for all the other positions-1.Example 3:
Input: n = 4, p = 2, banned = [0,1,3], k = 1
Output: [-1,-1,0,-1]
Explanation: In this case we can only perform reverse operations of size 1.So the 1 never changes its position.
Constraints:
1 <= n <= 1050 <= p <= n - 10 <= banned.length <= n - 10 <= banned[i] <= n - 11 <= k <= nbanned[i] != p- all values in
bannedare unique
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description int[]minReverseOperations(int n, int p, int[] banned, int k)
-