fork download
  1. import java.util.Arrays;
  2.  
  3. public class Main {
  4. public static int solution(int[] A, int N, int X, int Y, int Z) {
  5. Arrays.sort(A);
  6. int[] fuelDispensers = {X, Y, Z};
  7. int maxWaitingTime = 0;
  8.  
  9. for (int i = 0; i < N; i++) {
  10. int fuelDemand = A[i];
  11. int minTime = Integer.MAX_VALUE;
  12. int minIndex = -1;
  13.  
  14. // Find the dispenser with minimum waiting time
  15. for (int j = 0; j < 3; j++) {
  16. int waitTime = Math.max(0, fuelDemand - fuelDispensers[j]);
  17. if (waitTime < minTime) {
  18. minTime = waitTime;
  19. minIndex = j;
  20. }
  21. }
  22.  
  23. // If there's no dispenser with enough fuel, return -1
  24. if (minTime == Integer.MAX_VALUE)
  25. return -1;
  26.  
  27. fuelDispensers[minIndex] -= fuelDemand;
  28. maxWaitingTime = Math.max(maxWaitingTime, minTime);
  29. }
  30.  
  31. return maxWaitingTime;
  32. }
  33.  
  34. public static void main(String[] args) {
  35. int[] A = {2, 8, 4, 3, 2};
  36. int N = 5;
  37. int X = 7, Y = 11, Z = 3;
  38.  
  39. int result = solution(A, N, X, Y, Z);
  40. if (result == -1) {
  41. System.out.println("Car cannot refuel due to insufficient fuel.");
  42. } else {
  43. System.out.println(result);
  44. }
  45. }
  46. }
  47.  
Success #stdin #stdout 0.08s 52684KB
stdin
5
2 8 4 3 2
7 11 3
stdout
1