there was a party.there was a log register in which entry and exit time of all the guests was logged.you have to tell the time at which there was maximum guest in the party.
input will be the entry and exit time of all the n guests [1,4] [2,5] [9,12] [5,9] [5,12]
the output will be t=5 as there was maximum 3 guest were there namly guest(starting from 1) 2,4 and 5.
what i tried so far is
main()
{
int ret;
int a[5]={1,2,9,5,5};
int b[5]={4,6,12,9,12};
int i,j;
int runs=5;
int cur = 0,p1 = 0,p2 = 0;
printf("input is ");
for(i=0;i<5;i++)
{
printf("(");
printf("%d,%d",a[i],b[i]);
printf(")");
}
while(runs--)
{
while(p1<5 && p2<5)
{
if(a[p1] <= b[p2])
{
cur ++;
p1 ++ ;
}
else {
cur --;
p2 ++ ;
}
ret = cur ;
}
}
printf("\n the output is %d",ret);
}
i am getting 3 as output..which is completely wrong! where am i making error?
Several things are problematic with your code. Here’s a few pointers on where to improve it:
Your algorithm itself is doubtful. Assume that your first guest is the party host and stays from 1 until the end time of the party. With your current code,
p2will never change and you will ignore all other guests’ leave times.Even if your algorithm worked, it would assume that your input is sorted. By iterating
p1/p2you implicitly assume growing times in your array, which is already wrong for your sample input. So you ought to sort the input first.You are assigning the result
retat each iteration of your main loop. This neglects the fact on whether the current state (cur) is the maximum number of guests or not. Hint: If yo are to compute a maximum of something and don’t have any maximum computation in your code, there may be something missing.Here’s a different idea: Assuming you can spare an array of size maxtime, create an array filled with 0s. Process your input by increment the array at a certain time, if a guest arrives, and decrement it when a guest leaves. For example, the first 5 minutes would then look like
[1, 1, 0, -1, 1, ...]. Then it’s much simpler to walk linearly through the array and compute the maximum prefix sum. It’s also much easier this way to compute the full time-interval for how long this maximum number of guests was present.(If you want to go more fancy and have a much larger total time interval to cover, instead rely on a map with times as keys. Initialize like the array, then process the keys in sorted order.)