Imagine a party. Many guests are coming. You want to calculate the maximum number of guests in the party hall at a particular time given to you.
How will you do this????
First, Get the inputs. The inputs are two array of integers
given below.
‘arrive[]’ – This represents the guests who enters the party
hall at that time.
‘depart[]’ – This represents the guests who leaves the party
hall at that moment.
Note:
Always check both array’s length should be same in size.
Arrival entry should be entered in ‘arrive[]’ and Departure
entry should be noted in ‘depart[]’.
Algorithm:
- Get the inputs ‘arrive[]’ and ‘depart[]’;
- Sort the arrays.
- Let us declare two pointers ‘i’ and ‘j’. ‘i’ points arrive[] and ‘j’ points depart[].
- Call the function finditMaxGuests()
- This function check the condition to proceed.
- If arrive[i]<=depart[j] then, a guest came into the party hall. Increase the count of arrive[].
- Otherwise, decrease the count of depart and move on.
- Finally, print the value of maximum guests in the party at a particular time.
Here, is the program.
import java.util.Arrays;
import java.util.Scanner;
public class MeetingMaxGuestsEg {
public static void
main(String[] args) {
Scanner
scanner1 = new Scanner(System.in);
System.out.print("Enter number of guests arrived: ");
int no =
scanner1.nextInt();
int[] arrive
= new int[no];
for (int i =
0; i < no; i++)
{
System.out.print("Enter the next one: ");
arrive[i] =
scanner1.nextInt();
}
Scanner scanner2 = new Scanner(System.in);
System.out.print("Enter number of guests leaved: ");
int no1 =
scanner2.nextInt();
int[] depart
= new int[no];
for (int i =
0; i < no1; i++)
{
System.out.print("Enter the next one: ");
depart[i] =
scanner2.nextInt();
}
System.out.println("Maximum number of guests at the party: " +
finditMaxGuests(arrive, depart));
}
Arrays.sort(arrive);
Arrays.sort(depart);
int mGuests = 0;
int cGuests =
0;
int i = 0, j =
0;
while (i < arrive.length && j < depart.length) {
if
(arrive[i] <= depart[j]) {
cGuests++;
mGuests = Math.max(mGuests, cGuests);
i++;
} else {
cGuests--;
j++;
}
}
return
mGuests;
}
}
Output:
C:\raji\blog>javac MeetingMaxGuestsEg.java
C:\raji\blog>java MeetingMaxGuestsEg
Enter number of guests arrived: 10
Enter the next one: 1
Enter the next one: 3
Enter the next one: 5
Enter the next one: 7
Enter the next one: 9
Enter the next one: 11
Enter the next one: 15
Enter the next one: 2
Enter the next one: 4
Enter the next one: 6
Enter number of guests leaved: 4
Enter the next one: 6
Enter the next one: 3
Enter the next one: 45
Enter the next one: 34
Maximum number of guests at the party: 2
That’s all. The java program to find the maximum guests in
the party is clearly written. Keep coding!!!