Minimum Operations to Transform Array Problem
Description
LeetCode Problem 3724.
You are given two integer arrays nums1 of length n and nums2 of length n + 1.
You want to transform nums1 into nums2 using the minimum number of operations.
You may perform the following operations any number of times, each time choosing an index i:
- Increase
nums1[i]by 1. - Decrease
nums1[i]by 1. - Append
nums1[i]to the end of the array.
Return the minimum number of operations required to transform nums1 into nums2.
Example 1:
Input: nums1 = [2,8], nums2 = [1,7,3]
Output: 4
Explanation:
Step i Operation nums1[i] Updated nums1
1 0 Append - [2, 8, 2]
2 0 Decrement Decreases to 1 [1, 8, 2]
3 1 Decrement Decreases to 7 [1, 7, 2]
4 2 Increment Increases to 3 [1, 7, 3]
Thus, after 4 operations nums1 is transformed into nums2.
Example 2:
Input: nums1 = [1,3,6], nums2 = [2,4,5,3]
Output: 4
Explanation:
Step i Operation nums1[i] Updated nums1
1 1 Append - [1, 3, 6, 3]
2 0 Increment Increases to 2 [2, 3, 6, 3]
3 1 Increment Increases to 4 [2, 4, 6, 3]
4 2 Decrement Decreases to 5 [2, 4, 5, 3]
Thus, after 4 operations nums1 is transformed into nums2.
Example 3:
Input: nums1 = [2], nums2 = [3,4]
Output: 3
Explanation:
Step i Operation nums1[i] Updated nums1
1 0 Increment Increases to 3 [3]
2 0 Append - [3, 3]
3 1 Increment Increases to 4 [3, 4]
Thus, after 3 operations nums1 is transformed into nums2.
Constraints:
1 <= n == nums1.length <= 10^5nums2.length == n + 11 <= nums1[i], nums2[i] <= 10^5
Solution
Approach: Greedy
The array nums2 has one more element than nums1, so exactly one append is needed: that is 1 operation, and the appended copy must end up equal to nums2[n] (the last element).
For the first n positions, every nums1[i] has to be moved to nums2[i], costing |nums1[i] - nums2[i]|. The appended element is a copy of some nums1[i], and it can be copied at the moment when nums1[i] passes through the value nums2[n] while it is being moved to nums2[i]. That is free when nums2[n] lies between nums1[i] and nums2[i], so no extra cost is needed.
If no position has nums2[n] inside its interval, we have to take the position whose interval endpoint is closest to nums2[n] and pay that distance d extra. So the answer is 1 + sum of |nums1[i] - nums2[i]|, plus d only when no interval contains nums2[n].
Complexity: time O(n), space O(1), where n is the length of nums1.
from math import inf
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
ans = 1
ok = False
d = inf
for x, y in zip(nums1, nums2):
if x < y:
x, y = y, x
ans += x - y
d = min(d, abs(x - nums2[-1]), abs(y - nums2[-1]))
ok = ok or y <= nums2[-1] <= x
if not ok:
ans += d
return ans