- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 32 lines of Java from the credited upstream file 1776.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public double[] getCollisionTimes(int[][] cars) {3 double[] ans = new double[cars.length];4 Deque<Car> stack = new ArrayDeque<>();5 6 for (int i = cars.length - 1; i >= 0; --i) {7 final int pos = cars[i][0];8 final int speed = cars[i][1];9 while (!stack.isEmpty() &&10 (speed <= stack.peek().speed ||11 getCollisionTime(stack.peek(), pos, speed) >= stack.peek().collisionTime))12 stack.pop();13 if (stack.isEmpty()) {14 stack.push(new Car(pos, speed, Integer.MAX_VALUE));15 ans[i] = -1;16 } else {17 final double collisionTime = getCollisionTime(stack.peek(), pos, speed);18 stack.push(new Car(pos, speed, collisionTime));19 ans[i] = collisionTime;20 }21 }22 23 return ans;24 }25 26 private record Car(int pos, int speed, double collisionTime) {}27 28 private double getCollisionTime(Car car, int pos, int speed) {29 return (double) (car.pos - pos) / (speed - car.speed);30 }31}32