Largest Triangle Area in Python

Given a list of points on a plane, we need to find the area of the largest triangle that can be formed by any 3 of the points. This problem requires checking all possible combinations of three points and calculating their triangle areas.

So, if the input is like [[0,0],[0,1],[1,0],[0,2],[2,0]], then the output will be 2.0

(0,0) (0,1) (1,0) (0,2) (2,0) Largest Triangle Points: (0,2), (0,0), (2,0) Area = 2.0

Algorithm

To solve this, we will follow these steps ?

  • Initialize res = 0 to store maximum area
  • Get the number of points N
  • Use three nested loops to check all combinations of 3 points
  • For each combination, calculate triangle area using the formula: 0.5 * |x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)|
  • Keep track of the maximum area found
  • Return the maximum area

Triangle Area Formula

The area of a triangle with vertices at coordinates (x1,y1), (x2,y2), and (x3,y3) can be calculated using the cross product formula ?

Area = 0.5 * |x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)|

Example

class Solution:
    def largestTriangleArea(self, points):
        res = 0
        N = len(points)
        for i in range(N - 2):
            for j in range(i + 1, N - 1):
                for k in range(i + 2, N):
                    (x1, y1), (x2, y2), (x3, y3) = points[i], points[j], points[k]
                    res = max(res, 0.5 * abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)))
        return res

# Test the solution
ob = Solution()
points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
result = ob.largestTriangleArea(points)
print(f"Largest triangle area: {result}")
Largest triangle area: 2.0

How It Works

The algorithm uses three nested loops to generate all possible combinations of three points. For the given example with 5 points, it checks combinations like:

  • Points (0,0), (0,1), (1,0) ? Area = 0.5
  • Points (0,0), (0,1), (0,2) ? Area = 0 (collinear points)
  • Points (0,2), (0,0), (2,0) ? Area = 2.0 (maximum)

Time and Space Complexity

  • Time Complexity: O(N³) where N is the number of points
  • Space Complexity: O(1) as we only use a constant amount of extra space

Conclusion

This solution efficiently finds the largest triangle area by checking all possible combinations of three points using the cross product formula. The algorithm has O(N³) time complexity but provides an exact solution for the maximum triangle area problem.

Updated on: 2026-03-25T08:51:18+05:30

755 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements