#3588
Find Maximum Area of a Triangle
MediumArrayHash TableMathGreedyGeometryEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can optimize by grouping points based on their x and y coordinates. This allows us to quickly find potential triangles without checking every combination.
⚙️
Algorithm
3 steps- 1Step 1: Group points by their x-coordinates and y-coordinates.
- 2Step 2: For each unique x and y, find the maximum and minimum y values to form potential triangles.
- 3Step 3: Calculate the area using the base and height derived from these points.
solution.py19 lines
1from collections import defaultdict
2
3def maxArea(coords):
4 x_map = defaultdict(list)
5 y_map = defaultdict(list)
6 for x, y in coords:
7 x_map[x].append(y)
8 y_map[y].append(x)
9 max_area = -1
10 for x in x_map:
11 if len(x_map[x]) >= 2:
12 y_values = sorted(x_map[x])
13 base = y_values[-1] - y_values[0]
14 for y in y_map:
15 if len(y_map[y]) >= 2:
16 x_values = sorted(y_map[y])
17 height = x_values[-1] - x_values[0]
18 max_area = max(max_area, base * height)
19 return max_area if max_area != -1 else -1ℹ
Complexity note: We group points in O(n) and sort them, leading to O(n log n) complexity.
- 1Triangles with sides parallel to axes can be formed by grouping points.
- 2Sorting y-values and x-values helps in quickly calculating base and height.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.