Enumerate every point triple and use the absolute two-dimensional cross product to compute twice its area.
Complexity
O(n^3) time and O(1) extra space.
Find the maximum area of a triangle formed by any three supplied points.
Enumerate every point triple and use the absolute two-dimensional cross product to compute twice its area.
O(n^3) time and O(1) extra space.
package main
func largestTriangleArea(points [][]int) float64 {
twiceArea := 0
for i := 0; i < len(points); i++ {
for j := i + 1; j < len(points); j++ {
for k := j + 1; k < len(points); k++ {
area := absArea((points[j][0]-points[i][0])*(points[k][1]-points[i][1]) - (points[j][1]-points[i][1])*(points[k][0]-points[i][0]))
if area > twiceArea {
twiceArea = area
}
}
}
}
return float64(twiceArea) / 2
}
func absArea(value int) int {
if value < 0 {
return -value
}
return value
}
class Solution:
def largestTriangleArea(self, points: list[list[int]]) -> float:
twice_area = 0
for i in range(len(points)):
for j in range(i + 1, len(points)):
for k in range(j + 1, len(points)):
area = abs((points[j][0] - points[i][0]) * (points[k][1] - points[i][1]) - (points[j][1] - points[i][1]) * (points[k][0] - points[i][0]))
twice_area = max(twice_area, area)
return twice_area / 2
function largestTriangleArea(points: number[][]): number {
let twiceArea = 0;
for (let i = 0; i < points.length; i += 1) for (let j = i + 1; j < points.length; j += 1) for (let k = j + 1; k < points.length; k += 1) {
const area = Math.abs((points[j][0] - points[i][0]) * (points[k][1] - points[i][1]) - (points[j][1] - points[i][1]) * (points[k][0] - points[i][0]));
twiceArea = Math.max(twiceArea, area);
}
return twiceArea / 2;
}