<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>

"""
Naive solution: look at all lines defined by a pair of points and check how many points on that line
O(n^2*n)

Can I do O(n)? No
- must decide whether a point is or is not on the longest line

O(n^2)?
- iterate through all pairs of points and encode line
- count line that is most popular

But hmm this is O(n^2) space

Points lie on integer lattice.

y = mx + b
b = y - mx

If a line has n points it has (n choose 2) pairs of points?
(n choose 2) = n(n-1)/2 = n^2/2 - n/2
c = n(n-1)/2 <==> 0 = n^2 - n - 2c <==> n = (1 + sqrt(1+8c)) / 2
"""
from collections import defaultdict

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        if len(points) == 1:
            return 1
        lines = defaultdict(int)
        for i in range(len(points)):
            for j in range(i+1, len(points)):
                p1, p2 = points[i], points[j]
                if p1[0] != p2[0] or p1[1] != p2[1]:
                    if p2[0] < p1[0]:
                        t = p2
                        p2 = p1
                        p1 = t
                    if p1[0] == p2[0]:
                        m = "inf"
                        b = p1[0]
                        lines[f"({m},{b:.5f})"] += 1
                    else:
                        m = (p2[1]-p1[1])/(p2[0]-p1[0])
                        b = p2[1] - m*p2[0]
                        lines[f"({m:.5f},{b:.5f})"] += 1
        n_choose_2 = max(list(lines.values()))
        n = int((1 + sqrt(1+8*n_choose_2)) // 2)
        return n
                
22838