3190. Minimum Operations to Maximize Last Elements in Arrays
My accepted Python solution to LeetCode problem 3190, Minimum Operations to Maximize Last Elements in Arrays, running in 7ms.
- Difficulty: Medium
- Python
- Runtime 7ms
- Memory 17.5MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 7ms, memory 17.5MB, accepted 2025-12-31.
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
def solve(last1, last2):
# Try to make nums1[-1] = last1 and nums2[-1] = last2
ops = 0
for i in range(n - 1): # Don't include last element
a, b = nums1[i], nums2[i]
# a must be <= last1 and b must be <= last2
if a <= last1 and b <= last2:
continue
# Try swapping
if b <= last1 and a <= last2:
ops += 1
else:
return float('inf')
return ops
# Case 1: keep last elements as they are
res1 = solve(nums1[-1], nums2[-1])
# Case 2: swap last elements
res2 = solve(nums2[-1], nums1[-1]) + 1
ans = min(res1, res2)
return ans if ans != float('inf') else -1