Minimum Operations to Maximize Last Elements in Arrays — LeetCode 2934 Python Solution

MediumArrayEnumeration
Problem
#2934
Reading time
3 min

The problem

You are given two 0-indexed integer arrays, nums1 and nums2, both having length n. You are allowed to perform a series of operations (possibly none).

Example

Input
nums1 = [1,2,7], nums2 = [4,5,3]
Output
1
Explanation
In this example, an operation can be performed using index i = 2.

Python solution

Python
class Solution:
    def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
        def f(x: int, y: int) -> int:
            cnt = 0
            for a, b in zip(nums1[:-1], nums2[:-1]):
                if a <= x and b <= y:
                    continue
                if not (a <= y and b <= x):
                    return -1
                cnt += 1
            return cnt

        a, b = f(nums1[-1], nums2[-1]), f(nums2[-1], nums1[-1])
        return -1 if a + b == -2 else min(a, b + 1)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2934. Minimum Operations to Maximize Last Elements in Arrays?
LeetCode 2934. Minimum Operations to Maximize Last Elements in Arrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2934. Minimum Operations to Maximize Last Elements in Arrays?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2934. Minimum Operations to Maximize Last Elements in Arrays?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2934. Minimum Operations to Maximize Last Elements in Arrays cover?
LeetCode 2934. Minimum Operations to Maximize Last Elements in Arrays is tagged Array and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview