Created
August 7, 2022 18:18
-
-
Save svaza/11de0442a567438ed08dc42d68b74705 to your computer and use it in GitHub Desktop.
The Latest Time to Catch a Bus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int LatestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) { | |
PriorityQueue<int, int> qbus = new(); | |
PriorityQueue<int, int> qpass = new(); | |
HashSet<int> set = new(); | |
foreach(var bus in buses) qbus.Enqueue(bus, bus); | |
foreach(var p in passengers) | |
{ | |
qpass.Enqueue(p, p); | |
set.Add(p); | |
} | |
while(qbus.Count > 0) | |
{ | |
int lbus = qbus.Dequeue(); | |
int c = capacity; | |
int lastp = 0; | |
while(c > 0) | |
{ | |
if(qpass.Count > 0 && qpass.Peek() <= lbus) | |
{ | |
lastp = qpass.Dequeue(); | |
c--; | |
} else break; | |
} | |
// for the last bus | |
if(qbus.Count == 0) | |
{ | |
if(lastp == 0) return lbus; | |
if(c > 0) | |
{ | |
int res = 0; | |
for(int i = lastp+1; i <= lbus; i++) | |
{ | |
if(set.Contains(i)) continue; | |
res = i; | |
} | |
if(res > 0) return res; | |
} | |
for(int i = lastp-1; i >= 0; i--) | |
{ | |
if(set.Contains(i)) continue; | |
return i; | |
} | |
} | |
} | |
return -1; | |
} | |
} | |
/* | |
nlogn+nlogn+n | |
10 - 4 | |
20 - 11,13 | |
30 - { 19,21,25,26 } | |
10 - 2 | |
20 - { 17, 18, 19 } | |
latest time's passengers -> capacity'th passenger -- untill there is a space | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment