#2934
Minimum Operations to Maximize Last Elements in Arrays
MediumArrayEnumerationArrayEnumeration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach focuses on determining the minimum swaps needed by directly checking the conditions for each index without unnecessary iterations. This method is efficient and leverages the properties of the problem.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the maximum values of nums1 and nums2.
- 2Step 2: Initialize a counter for operations.
- 3Step 3: Iterate through each index and check the conditions for swaps.
- 4Step 4: If a swap is needed, increment the counter.
- 5Step 5: Return the counter if both conditions are met, otherwise return -1.
solution.py20 lines
1# Full working Python code
2
3def min_operations(nums1, nums2):
4 n = len(nums1)
5 max1 = max(nums1)
6 max2 = max(nums2)
7 operations = 0
8
9 if nums1[n-1] != max1 and nums2[n-1] != max2:
10 return -1
11
12 for i in range(n):
13 if nums1[i] <= max1 and nums2[i] <= max2:
14 continue
15 elif nums1[i] <= max2 and nums2[i] <= max1:
16 operations += 1
17 else:
18 return -1
19
20 return operationsℹ
Complexity note: The complexity is O(n) because we only iterate through the arrays a single time to check conditions, making it efficient.
- 1Both conditions must be checked simultaneously to ensure that the last elements of both arrays are maximized.
- 2The problem can be simplified by focusing on the maximum values and the conditions for each index.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.