3724. Minimum Operations to Transform Array
>
Hint
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: long long minOperations(vector<int>& nums1, vector<int>& nums2) { long long res = LLONG_MAX, base = 0; for(int i = 0; i < nums1.size(); i++) base += abs(nums1[i] - nums2[i]); for(int i = 0; i < nums1.size(); i++) { long long now = base - abs(nums1[i] - nums2[i]) + 1; int lo = nums2[i], hi = nums2.back(); if(lo > hi) swap(lo, hi); if(lo <= nums1[i] and nums1[i] <= hi) { now += abs(nums1[i] - lo) + abs(nums1[i] - hi); } else { now += max(abs(nums1[i] - lo), abs(nums1[i] - hi)); } res = min(res, now); } return res; } };
|