- 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
- 55 lines of Java from the credited upstream file 3102.java.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 int minimumDistance(int[][] points) {3 final int[] maxIndices = maxManhattanDistance(points, -1);4 final int[] xiyi = maxManhattanDistance(points, maxIndices[0]);5 final int[] xjyj = maxManhattanDistance(points, maxIndices[1]);6 return Math.min(manhattan(points, xiyi[0], xiyi[1]), 7 manhattan(points, xjyj[0], xjyj[1]));8 }9 10 11 12 private int[] maxManhattanDistance(int[][] points, int excludedIndex) {13 int minSum = Integer.MAX_VALUE;14 int maxSum = Integer.MIN_VALUE;15 int minDiff = Integer.MAX_VALUE;16 int maxDiff = Integer.MIN_VALUE;17 int minSumIndex = -1;18 int maxSumIndex = -1;19 int minDiffIndex = -1;20 int maxDiffIndex = -1;21 22 for (int i = 0; i < points.length; ++i) {23 if (i == excludedIndex)24 continue;25 final int x = points[i][0];26 final int y = points[i][1];27 final int sum = x + y;28 final int diff = x - y;29 if (sum < minSum) {30 minSum = sum;31 minSumIndex = i;32 }33 if (sum > maxSum) {34 maxSum = sum;35 maxSumIndex = i;36 }37 if (diff < minDiff) {38 minDiff = diff;39 minDiffIndex = i;40 }41 if (diff > maxDiff) {42 maxDiff = diff;43 maxDiffIndex = i;44 }45 }46 47 return maxSum - minSum >= maxDiff - minDiff ? new int[] {minSumIndex, maxSumIndex}48 : new int[] {minDiffIndex, maxDiffIndex};49 }50 51 private int manhattan(int[][] points, int i, int j) {52 return Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);53 }54}55