You are given the arrival and leaving times of n customers in a restaurant.
What was the maximum number of customers?
Example:
Input: n = 3, arr = {{5, 8}, {2, 4}, {3, 9}}
Output: 2
Approach
Java
import java.util.HashMap;public class RestaurantCustomers {public static void main(String[] args) {int n = 3;int[][] arr = { { 5, 8 }, { 2, 4 }, { 3, 9 } };restaurantCustomers(n, arr);}static void restaurantCustomers(int n, int[][] arr) {HashMap<Integer, Integer> mp = new HashMap<Integer,Integer>();for (int i = 0; i < n; i++) {int l = arr[i][0], r = arr[i][1];mp.put(l, mp.getOrDefault(l, 0) + 1);mp.put(r + 1, mp.getOrDefault(r + 1, 0) - 1);}int ans = 0, cur = 0;for (HashMap.Entry<Integer, Integer> set :mp.entrySet()) {cur += set.getValue();ans = Math.max(ans, cur);}System.out.println(ans);}}
C++
#include <bits/stdc++.h>using namespace std;void restaurantCustomers(int n, vector<vector<int>> &arr){map<int, int> mp;for (int i = 0; i < n; i++){int l = arr[i][0], r = arr[i][1];mp[l]++;mp[r + 1]--;}int ans = 0, cur = 0;for (auto it = mp.begin(); it != mp.end(); it++){cur += it->second;ans = max(ans, cur);}cout << ans << "\n";}int main(){int n = 3;vector<vector<int>> arr = {{5, 8}, {2, 4}, {3, 9}};restaurantCustomers(n, arr);return 0;}
No comments:
Post a Comment