2491-divide-players-into-teams-of-equal-skill.rs (2400B)
1/// You are given a positive integer array skill of even length n where 2/// skill[i] denotes the skill of the ith player. Divide the players into 3/// n / 2 teams of size 2 such that the total skill of each team is equal. 4/// 5/// The chemistry of a team is equal to the product of the skills of the 6/// players on that team. 7/// 8/// Return the sum of the chemistry of all the teams, or return -1 if there 9/// is no way to divide the players into teams such that the total skill 10/// of each team is equal. 11/// 12/// 13/// 14/// Example 1: 15/// 16/// Input: skill = [3,2,5,1,3,4] 17/// Output: 22 18/// Explanation: 19/// Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where 20/// each team has a total skill of 6. 21/// The sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 22/// = 5 + 8 + 9 = 22. 23/// 24/// Example 2: 25/// 26/// Input: skill = [3,4] 27/// Output: 12 28/// Explanation: 29/// The two players form a team with a total skill of 7. 30/// The chemistry of the team is 3 * 4 = 12. 31/// 32/// Example 3: 33/// 34/// Input: skill = [1,1,2,3] 35/// Output: -1 36/// Explanation: 37/// There is no way to divide the players into teams such that the total skill 38/// of each team is equal. 39/// 40/// 41/// 42/// Constraints: 43/// 44/// 2 <= skill.length <= 105 45/// skill.length is even. 46/// 1 <= skill[i] <= 1000 47use leetcode::arg_into; 48 49struct Solution {} 50 51impl Solution { 52 pub fn divide_players(mut skill: Vec<i32>) -> i64 { 53 skill.sort_unstable(); 54 if skill.is_empty() { 55 return 0; 56 } 57 let mut front: usize = 0; 58 let mut back: usize = skill.len() - 1; 59 let first = skill[front] as i64 + skill[back] as i64; 60 let mut chemistry = skill[front] as i64 * skill[back] as i64; 61 while back > 1 { 62 front += 2; 63 back -= 2; 64 if skill[front] as i64 + skill[back] as i64 != first { 65 return -1; 66 } 67 chemistry += skill[front] as i64 * skill[back] as i64; 68 } 69 chemistry 70 } 71} 72 73fn main() { 74 println!("{}", Solution::divide_players(arg_into(1))); 75} 76 77#[cfg(test)] 78mod tests { 79 use crate::Solution; 80 use leetcode::vi; 81 82 #[test] 83 fn test() { 84 assert_eq!(Solution::divide_players(vi("[3,2,5,1,3,4]")), 22); 85 assert_eq!(Solution::divide_players(vi("[3,4]")), 12); 86 assert_eq!(Solution::divide_players(vi("[1,1,2,3]")), -1); 87 } 88}