Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Below is the code to find the minimum average waiting time for customers at a store. I want improve the time complexity of the code. As an overview of the logic, I start from currentTime = 0 and increment it by preparation time of the current order (as only one order can be prepared at any given time). When that order is complete, look for customers whose order/arrival time is before or equal to the current time. It goes on till all the customers are served.

    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    Scanner scanner = new Scanner(fileReader);
    int noOfCustomers = scanner.nextInt();
    int[] arrivalTime = new int[noOfCustomers];
    int[] orderPreparationTime = new int[noOfCustomers];
    int i = 0;
    while (scanner.hasNext()) {
        arrivalTime[i] = scanner.nextInt();
        orderPreparationTime[i] = scanner.nextInt();
        i++;
    }

    int[] weightTimes = new int[noOfCustomers];
    int customersServed = 0;
    int currentTime = 0;
    while (customersServed < noOfCustomers) {
        int minWeightTime = Integer.MAX_VALUE;
        int customerIndex = Integer.MIN_VALUE;
        int preparationTime = 0;               
        for (int j = 0; j < noOfCustomers; j++) {
            if (arrivalTime[j] <= currentTime) {
                int weightTime = (currentTime - arrivalTime[j] + orderPreparationTime[j]);
                if (weightTime < minWeightTime) {
                    minWeightTime = weightTime;
                    customerIndex = j;
                    preparationTime = orderPreparationTime[j];
                }
            }
        }
        if (customerIndex != Integer.MIN_VALUE) {                    
            weightTimes[customerIndex] = minWeightTime;
            arrivalTime[customerIndex] = Integer.MAX_VALUE;
            customersServed++;
            currentTime += preparationTime;
        }
    }

    int totalWeightTime = 0;
    for (int weightTime : weightTimes) {
        totalWeightTime += weightTime;
    }
    System.out.println((int) totalWeightTime / noOfCustomers);

Input (Arrival Time, Order time) for 6 customers:

6
0 3
1 9
2 5
4 4
4 7 
5 3
share|improve this question
    
I assume that the input lists the customers chronologically by arrival time? –  200_success Jan 23 at 6:03
    
@200_success yes the arrival time & time to prepare her order. –  Meena Chaudhary Jan 23 at 6:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.