A CSharp solution


  • 0
    W

    Here is a simple C# solution.

    Idea is the same as the most voted solution.
    Start with first and second point, find their slope and save it in a dictionary (map). Do the same for all other pairs.
    Find the max after each iteration and compare with existing max

        public int MaxPoints(Point[] points) {
    
            if(points == null || points.Length == 0) return 0;
            int result = 0;
            for(int i=0; i<points.Length; i++)
            {
               int dups = 1, vertLine = 0, max = 0;
               Dictionary<int, int> slopeCount = new Dictionary<int, int>();
                for(int j=i+1; j<points.Length; j++)
                {
                    int x1 = points[i].x;
                    int x2 = points[j].x;
                    int y1 = points[i].y;
                    int y2 = points[j].y;
                    if(x1 == x2)
                    {
                        if(y1==y2) dups++;
                        else vertLine++;
                    }
                    else
                    {
                        int slope = (int)(10000 * ((double)y2 - y1) / (x2 - x1));
                        int slopeValue;
                        if(slopeCount.TryGetValue(slope, out slopeValue))
                        {
                            slopeCount[slope] = ++slopeValue;
                        }
                        else
                        {
                            slopeValue = 1;
                            slopeCount.Add(slope, 1);
                        }
                        
                        max = max > slopeValue ? max : slopeValue;
                    }
                }
                
                 max += dups;
                 vertLine += dups;
                 result = result >  max ? result : max;
                 result = result >  vertLine ? result : vertLine;
            }
            
            return result;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.