Rearranging Fruits — LeetCode 2561 Python Solution
HardGreedySortArrayHash Table
- Problem
- #2561
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket.
Example
- Input
- basket1 = [4,2,2,2], basket2 = [1,4,1,2]
- Output
- 1
- Explanation
- Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal.
Python solution
Python
class Solution:
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
cnt = Counter()
for a, b in zip(basket1, basket2):
cnt[a] += 1
cnt[b] -= 1
mi = min(cnt)
nums = []
for x, v in cnt.items():
if v % 2:
return -1
nums.extend([x] * (abs(v) // 2))
nums.sort()
m = len(nums) // 2
return sum(min(x, mi * 2) for x in nums[:m])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2561. Rearranging Fruits is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2561. Rearranging Fruits?
- LeetCode 2561. Rearranging Fruits is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2561. Rearranging Fruits?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2561. Rearranging Fruits?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2561. Rearranging Fruits cover?
- LeetCode 2561. Rearranging Fruits is tagged Greedy, Sort, Array and Hash Table on LeetCode.