- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 41 lines of Java from the credited upstream file 149.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 2 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 maxPoints(int[][] points) {3 int ans = 0;4 5 for (int i = 0; i < points.length; ++i) {6 Map<Pair<Integer, Integer>, Integer> slopeCount = new HashMap<>();7 int[] p1 = points[i];8 int samePoints = 1;9 int maxPoints = 0; 10 for (int j = i + 1; j < points.length; ++j) {11 int[] p2 = points[j];12 if (p1[0] == p2[0] && p1[1] == p2[1])13 ++samePoints;14 else {15 Pair<Integer, Integer> slope = getSlope(p1, p2);16 slopeCount.merge(slope, 1, Integer::sum);17 maxPoints = Math.max(maxPoints, slopeCount.get(slope));18 }19 }20 ans = Math.max(ans, samePoints + maxPoints);21 }22 23 return ans;24 }25 26 private Pair<Integer, Integer> getSlope(int[] p, int[] q) {27 final int dx = p[0] - q[0];28 final int dy = p[1] - q[1];29 if (dx == 0)30 return new Pair<>(0, p[0]);31 if (dy == 0)32 return new Pair<>(p[1], 0);33 final int d = gcd(dx, dy);34 return new Pair<>(dx / d, dy / y);35 }36 37 private int gcd(int a, int b) {38 return b == 0 ? a : gcd(b, a % b);39 }40}41