- 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
- 42 lines of C++ from the credited upstream file 149.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 int maxPoints(vector<vector<int>>& points) {4 int ans = 0;5 6 for (int i = 0; i < points.size(); ++i) {7 unordered_map<pair<int, int>, int, PairHash> slopeCount;8 const vector<int> p1{points[i]};9 int samePoints = 1;10 int maxPoints = 0; 11 for (int j = i + 1; j < points.size(); ++j) {12 const vector<int> p2{points[j]};13 if (p1 == p2)14 ++samePoints;15 else16 maxPoints = max(maxPoints, ++slopeCount[getSlope(p1, p2)]);17 }18 ans = max(ans, samePoints + maxPoints);19 }20 21 return ans;22 }23 24 private:25 pair<int, int> getSlope(const vector<int>& p, const vector<int>& q) {26 const int dx = p[0] - q[0];27 const int dy = p[1] - q[1];28 if (dx == 0)29 return {0, p[0]};30 if (dy == 0)31 return {p[1], 0};32 const int d = __gcd(dx, dy);33 return {dx / d, dy / d};34 }35 36 struct PairHash {37 size_t operator()(const pair<int, int>& p) const {38 return p.first ^ p.second;39 }40 };41};42