Skip to content

Commit b69ef3c

Browse files
authored
Merge pull request #3 from Drag0nop/Drag0nop-patch-2-1
Update rearranging_fruits.py
2 parents d6dcaf7 + b5633f1 commit b69ef3c

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed
Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,37 @@
1+
# it's a leetcode question no. 2561 where 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.
2+
# You want to make both baskets equal. To do so, you can use the following operation as many times as you want:
3+
4+
# Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.
5+
# The cost of the swap is min(basket1[i],basket2[j]).
6+
# Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.
7+
8+
# Return the minimum cost to make both the baskets equal or -1 if impossible.
9+
10+
from typing import List
11+
from collections import defaultdict
12+
113
class Solution:
214
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
315
n = len(basket1)
416
freq = defaultdict(int)
5-
mn = float("inf")
17+
mn = float('inf')
618
for i in range(n):
719
freq[basket1[i]] += 1
820
freq[basket2[i]] -= 1
921
mn = min(mn, basket1[i], basket2[i])
10-
22+
1123
to_swap = []
12-
for j, k in freq.items():
24+
for j,k in freq.items():
1325
if k % 2 != 0:
1426
return -1
1527
to_swap += [j] * (abs(k) // 2)
16-
28+
1729
to_swap.sort()
1830
res = 0
1931
for i in range(len(to_swap) // 2):
2032
res += min(to_swap[i], 2 * mn)
21-
33+
2234
return res
35+
36+
s = Solution()
37+
print(s.minCost([4, 2, 2, 2], [1, 4, 1, 2])) # Output: 1

0 commit comments

Comments
 (0)