Skip to content

Instantly share code, notes, and snippets.

  • Save codewithrajranjan/7fb8dd1843254701f17ae16d30974812 to your computer and use it in GitHub Desktop.
Save codewithrajranjan/7fb8dd1843254701f17ae16d30974812 to your computer and use it in GitHub Desktop.
You are given a list of data with following attributes start time, Rest Api name/service name, end time. You need to find maximum parallelism that got achieved. Example – {{1, A, 4}, {2, B, 3}, {4, C, 10}, {4, D, 7}, {2, E, 4}}. Answer here is 4 because at time t=4, there are 4 services running namely A, C, D, E respectively. I was asked to writ…
package selftuts;

import java.util.HashMap;

class Selftuts{

	public static void main(String[] args) {
		
		// this is the data in the format
		// startTime | Rest API or Service | endTime
		String[][] data = {
							{"1", "A", "4"}, 
							{"2", "B", "3"},
							{"4", "C", "10"},
							{"4", "D", "7"},
							{"2", "E", "4"}
						};
		
		// idea is to create  a HashMap whose key will be integer 
		// key will store the time units
		// value will store the frequency
		
		// for every data we will take integer time units and update the frequency
		// while updating the frequency we will maintain the time whose frequency is maximum
		
		HashMap<Integer,Integer> hmap = new HashMap<Integer,Integer>();

		int timeForMaxFrequency = 0; // this stores the time at which max parallelism there
		int maxFrequency = Integer.MIN_VALUE;

		for(int i=0;i<data.length;i++) {

			String[] eachData = data[i];

			int startTime = Integer.parseInt(eachData[0]);

			int endTime = Integer.parseInt(eachData[2]);

			for(int k=startTime;k<=endTime;k++) {

				if(hmap.containsKey(k)) {
					//if key is already present then we will update the frequency
					hmap.put(k, hmap.get(k)+1);
				}else {
					// if key is not present then we will add the key in HashMap with frequency as 1
					hmap.put(k, 1);
				}
				
				// checking if the frequency of current time is max then updating the values
				if(hmap.get(k)>maxFrequency) {
					maxFrequency = hmap.get(k);
					timeForMaxFrequency = k;
				}
			}
		}
		
		System.out.println(timeForMaxFrequency);
		
	}
}


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment