703489. Compatible friends
Compatible Friends
Summary
The problem is about finding compatible friends in a given list of students. Each student has a set of preferences for their ideal friends, and we need to find the maximum number of friends who can be paired up with each other based on these preferences. The key concepts involved are arrays and data structures.
Detailed Explanation
Given an array of integers students where each integer represents the preference of a student (e.g., 1-5), our task is to find the maximum number of students who can be paired up with each other based on their preferences. A pair of students is considered compatible if they have a matching preference.
Here's a step-by-step breakdown of the solution:
- First, we need to sort the array
studentsin descending order. This is because we want to prioritize pairing students with the highest preferences first. - Initialize two pointers,
iandj, to the start and end of the sorted array respectively. - Loop through the array until
imeets or crossesj. In each iteration:- If the preference at index
imatches the preference at indexj, increment bothiandjby 1. This means we've found a pair of compatible friends, so we increment their count. - If the preference at index
iis greater than the preference at indexj, decrementjby 1 to move towards the next potential friend with a higher preference. - Otherwise, increment
iby 1 to consider the next student with the same or lower preference.
- If the preference at index
- The maximum number of compatible friends found is the total count.
Time complexity: O(n log n) due to sorting Space complexity: O(1) as we only use a few variables
Optimized Solutions
Java
java
public int maxCompatibleFriends(int[] students) {
Arrays.sort(students);
int i = 0, j = students.length - 1;
int count = 0;
while (i <= j) {
if (students[i] == students[j]) {
count++;
i++;
j--;
} else if (students[i] > students[j]) {
j--;
} else {
i++;
}
}
return count;
}
Python
Not available