Minimum Operations to Reach Target Array
You are given two integer arrays, nums and target, of length n.
In one operation, you can:
- Choose any integer value x.
- Find all maximal contiguous segments in the array where nums[i] == x. (A segment is maximal if it cannot be extended left or right without including a number different from x).
- For every such segment [l, r], simultaneously update all its elements to match the target array: nums[l] = target[l], nums[l+1] = target[l+1], ..., nums[r] = target[r].
Return the minimum number of operations required to make the nums array strictly equal to the target array.
Example 1:
Input: nums = [8, 9, 8, 9], target = [1, 9, 2, 9]
Output: 1
Explanation:
Choosing x = 8 finds two maximal segments [0, 0] and [2, 2]. Updating them changes nums[0] to 1 and nums[2] to 2. nums is now [1, 9, 2, 9]. It takes 1 operation.
Example 2:
Input: nums = [5, 5, 5, 5], target = [5, 5, 5, 5]
Output: 0
Explanation:
nums is already equal to target, so 0 operations are required.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [3, 1, 3], target = [1, 3, 1]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n == nums.length == target.length <= 105
- 1 <= nums[i], target[i] <= 105