Find Maximum Area of a Triangle - Problem
You're tasked with finding the maximum area of a triangle from a collection of points on a 2D plane, but with a special constraint: at least one side of the triangle must be parallel to either the x-axis or y-axis.
Given a 2D array coords of size n Γ 2 representing coordinates of n points, you need to:
- Find three points that form a triangle with maximum area
- Ensure at least one side is horizontal (parallel to x-axis) or vertical (parallel to y-axis)
- Return twice the maximum area (this avoids floating-point precision issues)
- Return
-1if no valid triangle exists
Key insight: A triangle has a horizontal side when two points share the same y-coordinate, and a vertical side when two points share the same x-coordinate. The area is maximized by finding the point farthest from the shared coordinate line.
Input & Output
example_1.py β Basic Triangle
$
Input:
coords = [[0,0],[0,1],[1,0]]
βΊ
Output:
1
π‘ Note:
The triangle formed by points (0,0), (0,1), and (1,0) has a vertical side from (0,0) to (0,1) and a horizontal side from (0,0) to (1,0). The area is 0.5, so twice the area is 1.
example_2.py β Larger Triangle
$
Input:
coords = [[0,0],[2,0],[1,3]]
βΊ
Output:
6
π‘ Note:
The triangle has a horizontal base from (0,0) to (2,0) with length 2, and height 3 to point (1,3). Area = 0.5 Γ 2 Γ 3 = 3, so twice the area is 6.
example_3.py β No Valid Triangle
$
Input:
coords = [[1,1],[2,2],[3,3]]
βΊ
Output:
-1
π‘ Note:
All points lie on the same diagonal line, so no triangle can be formed with horizontal or vertical sides. Return -1 as no valid triangle exists.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Aligned Points
Group points that share x-coordinates (vertical alignment) or y-coordinates (horizontal alignment)
2
Find Maximum Bases
For each aligned group, find the pair of points with maximum distance to form the triangle's base
3
Optimize Third Vertex
For each base, find the third point that maximizes the perpendicular distance (height)
4
Calculate Maximum Area
Use the formula Area = Β½ Γ base Γ height, return twice the maximum area found
Key Takeaway
π― Key Insight: By leveraging the constraint that at least one side must be axis-aligned, we can reduce the problem from checking all O(nΒ³) triangles to efficiently computing optimal areas using coordinate grouping in O(nΒ²) time.
Time & Space Complexity
Time Complexity
O(nΒ²)
O(n) to build hash maps, then O(nΒ²) to find optimal triangles for each coordinate group
β Quadratic Growth
Space Complexity
O(n)
Hash maps to store coordinate groupings
β‘ Linearithmic Space
Constraints
- 3 β€ coords.length β€ 1000
- -104 β€ coords[i][0], coords[i][1] β€ 104
- At least one side of the triangle must be parallel to x-axis or y-axis
- Triangle must have non-zero area
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code