I solve a puzzle for a queue from an arbitrary number of customers at *n* cash registers in the supermarket, where the queue is specified by an array of integers, each of which means the time of service for the corresponding buyer at the cash register.
There was a problem in the most difficult case, when the number of cash desks is more than one ( n > 1 ) and the number of customers in the queue is greater than the number of cash desks ( customers.length > n ).
import java.util.Arrays; public class Solution { public static int solveSuperMarketQueue(int[] customers, int n) { int sum = 0; int[] nCustomers; int[] restOfCustomers; if (customers.length == 0) { return 0; } else if (customers.length == 1) { return customers[0]; } else { if (n == 0) { return 0; } else if (n == 1) { sum = sumOfArray(customers); } else if (customers.length <= n) { int customerMax = customers[0]; for (int i = 0; i < n; i++) { if (customers[i] > customerMax) { customerMax = customers[i]; } } return customerMax; } else { nCustomers = Arrays.copyOfRange(customers, 0, n); restOfCustomers = Arrays.copyOfRange(customers, n, customers.length); int serviceTime = 0; while (sumOfArray(nCustomers) > 0) { for (int i = 0; i < nCustomers.length; i++) { nCustomers[i]--; if (nCustomers[i] == 0) { nCustomers[i] = restOfCustomers[0]; restOfCustomers = Arrays.copyOfRange(restOfCustomers, 1, restOfCustomers.length); } serviceTime++; } return serviceTime; } } } return sum; } public static int sumOfArray(int ary[]) { int s = 0; for (int i = 0; i < ary.length; i++) { s += ary[i]; } return s; } } Namely this fragment:
} else { nCustomers = Arrays.copyOfRange(customers, 0, n); restOfCustomers = Arrays.copyOfRange(customers, n, customers.length); int serviceTime = 0; while (sumOfArray(nCustomers) > 0) { for (int i = 0; i < nCustomers.length; i++) { nCustomers[i]--; if (nCustomers[i] == 0) { nCustomers[i] = restOfCustomers[0]; restOfCustomers = Arrays.copyOfRange(restOfCustomers, 1, restOfCustomers.length); } serviceTime++; } return serviceTime; } Here I broke an array of customers from the condition of customers into two subarrays - nCustomers (these are the first n buyers that approached n cash registers) and restOfCustomers (this is the remaining queue).
My reasoning is this: as long as someone has a cash register, we start the serviceTime service time counter, decreasing each element of the nCustomers array for each iteration.
After each iteration, we check to see if any element in this array has zeroed, and if it is zeroed, we assign the first element from the subarray of the remaining restOfCustomers queue to restOfCustomers , and shorten this subarray itself to this element passed to nCustomers .
Tell me - was I mistaken in the logic of the decision, or was the logic correct, and was the implementation in the code incorrect?