Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
40 views3 pages

Car 1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 3

// Java code of the above approach

import java.io.*;
import java.util.*;
import java.util.function.Function;

class GFG {

// Function to calcuate minimum time required


static void minTimeRequired(int n, int m, int[] arr)
{

// cnt to count the total number of


// road the ith car is proficient in
int[] cnt = new int[n + 1];

// Calculating the total no. of


// proficient roads that each
// car can do
for (int i = 0; i < m; i++) {
cnt[arr[i]]++;
}

Function<Integer, Boolean> check = (time) ->


{
long free = 0, needed = 0;

for (int i = 1; i <= n; i++) {


if (time >= cnt[i]) {
// Storing the number of
// roads that can be done
// if the provided time is
// more than the number of
// efficient roads assigned
// to a car
long extraTime = (time - cnt[i]);

// We are dividing the


// difference by 2 because
// as it is mentioned in the
// question if the car is
// not proficient then 2
// sec are required to
// complete a road.
free += extraTime / 2;
}
else {
// Storing the number of
// roads that are left
needed += cnt[i] - time;
}
}

// If free road slots are greater


// than or equal to the needed,
// then it is possible to complete
// all m roads in the given time

return needed <= free;


};

// Maximum required time in worst


// case is 2 * m, if you assign all
// roads to a single car, and this car
// is not proficient in any of
// these roads.
int l = 0, r = 2 * m;
int minTime = -1;

// Binary Search on minTime


while (l <= r) {
int mid = (l + r) / 2;
if (check.apply(mid)) {
// If we are able to complete
// all roads using m unit of
// time then check with lesser
// time again
minTime = mid;

r = mid - 1;
}
else {
l = mid + 1;
}
}

System.out.println(minTime);
}
public static void main(String[] args)
{
int n = 2, m = 4;
int[] arr = { 1, 2, 1, 2 };

// Function call
minTimeRequired(n, m, arr);
}
}

// This code is contributed by lokeshmvs21.

You might also like