Find Maximum Area of a Triangle - Problem

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.

Input & Output

Example 1 — Basic Triangle
$ Input: coords = [[1,3],[5,3],[3,5]]
Output: 8
💡 Note: Points (1,3) and (5,3) form a horizontal side of length 4. The third point (3,5) is at distance 2 from this horizontal line. Area = 4 × 2 / 2 = 4. Return 2 × 4 = 8.
Example 2 — Vertical Side
$ Input: coords = [[2,1],[2,4],[6,2]]
Output: 12
💡 Note: Points (2,1) and (2,4) form a vertical side of length 3. The third point (6,2) is at distance 4 from this vertical line. Area = 3 × 4 / 2 = 6. Return 2 × 6 = 12.
Example 3 — No Valid Triangle
$ Input: coords = [[1,1],[2,3],[4,5]]
Output: -1
💡 Note: No two points share the same x or y coordinate, so no triangle can have an axis-parallel side. Return -1.

Constraints

  • 3 ≤ coords.length ≤ 1000
  • -109 ≤ coords[i][0], coords[i][1] ≤ 109
  • All coordinate pairs are unique

Visualization

Tap to expand
Find Maximum Triangle Area with Axis-Parallel Side(1,3)(5,3)(3,5)Horizontal side (y=3)height = 2base = 4CalculationArea = base × height / 2= 4 × 2 / 2 = 4Return 2 × Area = 8Output: 8
Understanding the Visualization
1
Input Points
Given coordinate points in 2D plane
2
Find Axis-Parallel Sides
Identify pairs sharing x or y coordinates
3
Calculate Areas
Compute triangle areas and return twice the maximum
Key Takeaway
🎯 Key Insight: For axis-parallel sides, two points must share identical x or y coordinates
Asked in
Google 25 Amazon 18 Microsoft 15
12.4K Views
Medium Frequency
~25 min Avg. Time
286 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen