#2499
Minimum Total Cost to Make Arrays Unequal
HardArrayHash TableGreedyCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a greedy approach to minimize the total cost by focusing on the indices where nums1 matches nums2. It ensures that we only swap when necessary and selects the least costly swaps.
⚙️
Algorithm
4 steps- 1Step 1: Create a list of indices where nums1[i] == nums2[i].
- 2Step 2: For each index in this list, find the minimum cost swap with an index that has a different value in nums1.
- 3Step 3: If no valid swaps can be made and there are still indices where nums1[i] == nums2[i], return -1.
- 4Step 4: Sum the costs of all swaps made.
solution.py17 lines
1def minCost(nums1, nums2):
2 n = len(nums1)
3 indices = [i for i in range(n) if nums1[i] == nums2[i]]
4 total_cost = 0
5 if len(indices) == 0:
6 return 0
7 for i in indices:
8 swap_found = False
9 for j in range(n):
10 if nums1[j] != nums2[i]:
11 nums1[i], nums1[j] = nums1[j], nums1[i]
12 total_cost += i + j
13 swap_found = True
14 break
15 if not swap_found:
16 return -1
17 return total_costℹ
Complexity note: The time complexity is O(n) because we only traverse the arrays a limited number of times, and the space complexity is O(n) due to storing indices of swaps.
- 1Greedily swap elements where nums1[i] == nums2[i] to minimize costs.
- 2If no valid swaps can be made, return -1.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.