Find Maximum Area of a Triangle Problem
Description
LeetCode Problem 3588.
You are given a 2D array coords of size n x 2, representing the coordinates of n points in an infinite Cartesian plane.
Find twice the maximum area of a triangle with its corners at any three elements from coords, such that at least one side of this triangle is parallel to the x-axis or y-axis. Formally, if the maximum area of such a triangle is A, return 2 * A.
If no such triangle exists, return -1.
Note that a triangle cannot have zero area.
Example 1:
Input: coords = [[1,1],[1,2],[3,2],[3,3]]
Output: 2
Explanation:

The triangle shown in the image has a base 1 and height 2. Hence its area is 1/2 * base * height = 1.
Example 2:
Input: coords = [[1,1],[2,2],[3,3]]
Output: -1
Explanation:
The only possible triangle has corners (1, 1), (2, 2), and (3, 3). None of its sides are parallel to the x-axis or the y-axis.
Constraints:
1 <= n == coords.length <= 10^51 <= coords[i][0], coords[i][1] <= 10^6- All
coords[i]are unique.
Solution
Approach: Fix the Axis-Parallel Side
The triangle must have a side parallel to an axis, and we only need twice the area, so base times height is enough.
Handle sides parallel to the y-axis first. For every x, a vertical side takes the lowest and highest y at that x (stored in two hash maps), giving a base maxY - minY. The third vertex should be as far away horizontally as possible, i.e. at the global minimum or maximum x, so the height is max(maxX - x, x - minX). Take the best product over all x.
Then swap the two coordinates of every point and repeat to cover sides parallel to the x-axis. If the best value is 0, no triangle exists and the answer is -1.
Complexity: O(n) time and O(n) space.
from math import inf
class Solution:
def maxArea(self, coords: List[List[int]]) -> int:
def calc() -> int:
mn, mx = inf, 0
f = {}
g = {}
for x, y in coords:
mn = min(mn, x)
mx = max(mx, x)
if x in f:
f[x] = min(f[x], y)
g[x] = max(g[x], y)
else:
f[x] = g[x] = y
ans = 0
for x, y in f.items():
d = g[x] - y
ans = max(ans, d * max(mx - x, x - mn))
return ans
ans = calc()
for c in coords:
c[0], c[1] = c[1], c[0]
ans = max(ans, calc())
return ans if ans else -1