Coverage for blog/dsa/leetcode/divide_players/__init__.py: 52%
44 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-20 16:23 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-20 16:23 +0000
1import pytest
4# start snippet solution
5class Solution:
7 # NOTE: Skill has positive elements and even length.
8 def dividePlayers(self, skill: list[int]) -> int:
10 s, n = sum(skill), len(skill)
11 n2 = n // 2
13 # NOTE: Must be divisible by n.
14 if s % n2:
15 return -1
17 # NOTE: Memo maps completions to their index in ``skill``.
18 target = s // n2
19 memo: dict[int, int] = {}
21 out = 0
22 for val in skill:
24 if (diff := target - val) <= 0:
25 return -1
26 elif val in memo:
27 memo[val] -= 1
28 out += val * diff
30 if memo[val] == 0:
31 memo.pop(val)
33 elif diff not in memo:
34 memo[diff] = 1
35 else:
36 memo[diff] += 1
38 if memo:
39 return -1
41 return out
42 # end snippet solution
45# start snippet sort
46class SolutionSort:
48 def dividePlayers(self, skill: list[int]) -> int:
50 skill.sort()
51 n = len(skill)
52 target = skill[0] + skill[n - 1]
54 out = 0
55 for k in range(n // 2):
56 j = n - 1 - k
57 a, b = skill[k], skill[j]
59 if a + b != target:
60 return -1
62 out += a * b
64 return out
65 # end snippet sort
68@pytest.fixture
69def solution():
70 return SolutionSort()
73@pytest.mark.parametrize(
74 "question, answer",
75 (
76 ([3, 2, 5, 1, 3, 4], 22),
77 ([3, 4], 12),
78 ([1, 1, 2, 3], -1),
79 ([2, 1, 5, 2], -1),
80 ([2, 3, 4, 2, 5, 5], 32),
81 ([10, 14, 16, 15, 9, 4, 4, 4], -1),
82 ),
83)
84def test_solution(
85 solution: Solution,
86 question: list[int],
87 answer: int,
88):
90 answer_computed = solution.dividePlayers(question)
91 assert answer == answer_computed