<p>Given an array of <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents a point on the <strong>X-Y</strong> plane, return <em>the maximum number of points that lie on the same straight line</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 3
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>Input:</strong> points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
<strong>Output:</strong> 4
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= points.length &lt;= 300</code></li>
	<li><code>points[i].length == 2</code></li>
	<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
	<li>All the <code>points</code> are <strong>unique</strong>.</li>
</ul>

import math

class LineCounter:

    def __init__(self):
        self._line_dict = {}
        self._max_count = 0
    
    def _least_terms(self, num, den):
        # Ensure that denominator is positive; if denominator is zero, than numerator should be positive
        if den < 0:
            num *= -1
            den *= -1
        elif den == 0:
            num = abs(num)
        
        # Put in least terms
        gcd = math.gcd(num, den)
        if gcd != 0:
            num //= gcd
            den //= gcd
        
        return num, den

    def _get_index(self, p1, p2):
        # f(t) = [at + c, bt + d]

        # Compute change in x, y
        dy, dx = self._least_terms(p2[1] - p1[1], p2[0] - p1[0])

        # Compute offset
        # (dy/dx)*x + b = y
        # dy*x + dx*b = dx*y
        # dx*b = dx*y - dy*x

        if dx == 0:
            bn, bd = p1[0], 1
        else:
            bn, bd = self._least_terms(dx*p1[1] - dy*p1[0], dx)

        return (dx, dy, bn, bd)

    def max(self):
        # n choose 2 = n(n+1)/2 = 1/2(n^2 + n) = m
        # n^2 + n - 2m = 0
        return (math.isqrt(8*self._max_count + 1) + 1)//2
    
    def increment(self, p1, p2):
        key = self._get_index(p1, p2)
        if key not in self._line_dict:
            self._line_dict[key] = 0
        
        self._line_dict[key] += 1

        if self._line_dict[key] > self._max_count:
            self._max_count = self._line_dict[key]

        return self._line_dict[key]

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        line_counter = LineCounter()
        for i,p1 in enumerate(points):
            for j in range(i+1, n):
                line_counter.increment(p1, points[j])
        
        return line_counter.max()

25616