Skip to content

Commit 178c6da

Browse files
authored
Update rearranging_fruits.py
1 parent faeb9ca commit 178c6da

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

greedy_methods/rearranging_fruits.py

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,35 @@
33

44

55
def min_cost(basket1: List[int], basket2: List[int]) -> int:
6+
"""
7+
Compute the minimum cost to make two baskets identical by swapping fruits.
8+
9+
Each fruit is represented by an integer value. The goal is to make both baskets
10+
have the same multiset of elements with the minimum swap cost. Each swap cost
11+
is defined as the minimum of the swapped fruit’s value and twice the smallest
12+
fruit value in both baskets.
13+
14+
If it's impossible to make the baskets identical, return -1.
15+
16+
Args:
17+
basket1 (List[int]): The first basket of fruits.
18+
basket2 (List[int]): The second basket of fruits.
19+
20+
Returns:
21+
int: The minimum total cost, or -1 if impossible.
22+
23+
Examples:
24+
>>> min_cost([4, 2, 2, 2], [1, 4, 1, 2])
25+
1
26+
>>> min_cost([1, 2, 3, 4], [2, 3, 4, 1])
27+
0
28+
>>> min_cost([1, 1, 1, 1], [1, 1, 1, 1])
29+
0
30+
>>> min_cost([1, 2, 2], [2, 1, 1])
31+
-1
32+
>>> min_cost([5, 3, 3, 2], [2, 5, 5, 3])
33+
-1
34+
"""
635
n = len(basket1)
736
freq: DefaultDict[int, int] = defaultdict(int)
837
mn: float = float("inf")
@@ -21,22 +50,12 @@ def min_cost(basket1: List[int], basket2: List[int]) -> int:
2150
to_swap.sort()
2251
res: int = 0
2352
for i in range(len(to_swap) // 2):
24-
# Ensure mn is treated as int during arithmetic
2553
res += min(to_swap[i], 2 * int(mn))
2654

2755
return res
2856

2957

3058
if __name__ == "__main__":
31-
# ---- Test Cases ----
32-
test_cases = [
33-
([4, 2, 2, 2], [1, 4, 1, 2]), # Expected: 1
34-
([1, 2, 3, 4], [2, 3, 4, 1]), # Expected: 0
35-
([1, 1, 1, 1], [1, 1, 1, 1]), # Expected: 0
36-
([1, 2, 2], [2, 1, 1]), # Expected: -1
37-
([5, 3, 3, 2], [2, 5, 5, 3]), # Expected: -1
38-
]
39-
40-
print("Running test cases...\n")
41-
for b1, b2 in test_cases:
42-
print(f"basket1 = {b1}, basket2 = {b2} → minCost = {min_cost(b1, b2)}")
59+
import doctest
60+
doctest.testmod()
61+
print("All doctests passed.")

0 commit comments

Comments
 (0)