aboutsummaryrefslogtreecommitdiff
path: root/divide_players_equal_skill.c
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-10-03 23:45:19 -0600
committerJack Sangdahl <[email protected]>2024-10-03 23:45:19 -0600
commit92867d838ca087431ddacbe3c438460922b8a871 (patch)
treee4a58b7441fddb96883b3afe0301b0a771cea2e4 /divide_players_equal_skill.c
parent82fb310c19c94b81f495458d5e653e9338d22858 (diff)
downloadleetcode-92867d838ca087431ddacbe3c438460922b8a871.tar.gz
leetcode-92867d838ca087431ddacbe3c438460922b8a871.zip
2491. divide players into teams of equal skill
Diffstat (limited to 'divide_players_equal_skill.c')
-rw-r--r--divide_players_equal_skill.c34
1 files changed, 34 insertions, 0 deletions
diff --git a/divide_players_equal_skill.c b/divide_players_equal_skill.c
new file mode 100644
index 0000000..9dc2ea9
--- /dev/null
+++ b/divide_players_equal_skill.c
@@ -0,0 +1,34 @@
+// 2491. Divide Players Into Teams of Equal Skill
+#include "leetcode.h"
+
+/*
+ * you are given a positive integer array 'skill' of even length 'n' where
+ * 'skill[i]' denotes the skill of the i'th player. divide the players into 'n /
+ * 2' teams of size '2' such that the total skill of each team is equal. the
+ * chemistry of team is equal to the product of the skills of the players on
+ * that team. return the sum of the chemistry of all the teams, or return -1 if
+ * there is no way to divide the players into teams such that the total skill of
+ * each team is equal
+ */
+
+int cmp(const void *a, const void *b) { return *((int *)a) - *((int *)b); }
+
+long long dividePlayers(int *skill, int skillSize) {
+ long long ans = 0, team;
+ qsort(skill, skillSize, sizeof(int), cmp);
+ team = skill[0] + skill[skillSize - 1];
+ for (int i = 0, j = skillSize - 1; i < j; i++, j--) {
+ if (skill[i] + skill[j] != team)
+ return -1;
+ else
+ ans += skill[i] * skill[j];
+ }
+ return ans;
+}
+
+int main() {
+ int s1[] = {3, 2, 5, 1, 3, 4}, s2[] = {3, 4}, s3[] = {1, 1, 2, 3};
+ printf("%lld\n", dividePlayers(s1, ARRAY_SIZE(s1))); // expect: 22
+ printf("%lld\n", dividePlayers(s2, ARRAY_SIZE(s2))); // expect: 12
+ printf("%lld\n", dividePlayers(s3, ARRAY_SIZE(s3))); // expect: -1
+}