We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Complete the flatlandSpaceStations function below.staticintflatlandSpaceStations(intn,int[]c){intnumberOfCities=n;intnumberOfStations=c.length;// Each city can have one station. If numberOfCities == numberOfStations. Each city has station so distance will be 0if(numberOfCities==numberOfStations){return0;}// If there is only station subtract 1 from numberOfCitiesif(numberOfStations==1){returnnumberOfCities-1;}/** * By default Priority queue gives priority to smaller elements. By using priority Queue we will be sure that we will always get the station in the * same order as we are traversing the cities. * * Suppose stations are given in order [4, 7, 1]. We will start iterating from city 0. City 0 till city 4 should check distance with spaceStationCity 1 * and spaceStationCity 4. * * After passing spaceStationCity 4 cities should check distance with spaceStationCity 4 and spaceStationCity 7. */PriorityQueue<Integer>spaceStationsCityPriorityQueue=newPriorityQueue<>();for(intspaceStationCity:c){spaceStationsCityPriorityQueue.add(spaceStationCity);}// At this point we know that there are atl-east 2 space stationsintspaceStationCity1=spaceStationsCityPriorityQueue.poll();intspaceStationCity2=spaceStationsCityPriorityQueue.poll();// We can also use max variable and check it instead of creating the array. But let's do it with array as questions is also showing the array.int[]distanceArr=newint[n];/** * * We have taken the first two stations. We are using priority queue. We know we will get the stations in order. * Start from city 0. * Check the city distance from space station 1 and space station 2. * Find the minimum of both distance. * Add minimum distance to distance array. * Once the space station city 2 reaches. Now change the space station city * */for(inti=0;i<numberOfCities;i++){intcity=i;intspaceStationCity1Distance=Math.abs(city-spaceStationCity1);intspaceStationCity2Distance=Math.abs(city-spaceStationCity2);intminSpaceStationDistance=Math.min(spaceStationCity1Distance,spaceStationCity2Distance);distanceArr[i]=minSpaceStationDistance;if(city==spaceStationCity2){spaceStationCity1=spaceStationCity2;if(spaceStationsCityPriorityQueue.isEmpty()){spaceStationCity2=0;}else{spaceStationCity2=spaceStationsCityPriorityQueue.poll();}}}intmaxDistance=findMax(distanceArr);returnmaxDistance;}publicstaticintfindMax(int[]arr){intmax=Integer.MIN_VALUE;for(intnumber:arr){if(number>max){max=number;}}returnmax;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Flatland Space Stations
You are viewing a single comment's thread. Return to all comments →