Largest Triangle Area Problem
Description
LeetCode Problem 812.
Given an array of points on the X-Y plane points where points[i] = [x_i, y_i], return the area of the largest triangle that can be formed by any three different points. Answers within 10^-5 of the actual answer will be accepted.
Example 1:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.
Example 2:
Input: points = [[1,0],[0,0],[0,1]]
Output: 0.50000
Constraints:
- 3 <= points.length <= 50
- -50 <= x_i, y_i <= 50
- All the given points are unique.
Solution
Approach: Try Every Triple
With at most 50 points there are fewer than 20,000 triples, so we can simply try all of them and keep the largest area.
For points (x1, y1), (x2, y2), (x3, y3), the area comes from the cross product of the two sides that start at the first point (the shoelace formula):
cross = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)
area = |cross| / 2
The sign of cross only tells whether the points go clockwise or counter-clockwise, so take the absolute value. Three points on one line give cross = 0, a triangle of area 0, which is handled without a special case.
Keep the largest |cross| as an integer and divide by 2 only at the end, so no floating-point error builds up. Loop with i < j < k so each triple is checked once.
Complexity: O(n3) time and O(1) space, where n is the number of points.
class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
n = len(points)
best_twice_area = 0 # twice the area keeps everything in integers
for i in range(n):
x1, y1 = points[i]
for j in range(i + 1, n):
x2, y2 = points[j]
for k in range(j + 1, n):
x3, y3 = points[k]
# Cross product of the two sides from point i: twice the signed area (shoelace formula).
cross = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)
best_twice_area = max(best_twice_area, abs(cross))
return best_twice_area / 2
Now write it from memory
Close the write-up and solve it yourself against the tests.