Skip to content

Commit ff7b05f

Browse files
committed
Time: 13 ms (47.37%), Space: 61.5 MB (42.11%) - LeetHub
1 parent e5631ba commit ff7b05f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Brute Force Triangle | 25 Lines | O(n³) | 6ms
2+
3+
# Intuition
4+
To find the largest triangle area, we need to check all possible combinations of 3 points from the given set and calculate their areas. The triangle with the maximum area is our answer.
5+
6+
# Approach
7+
Use a brute force approach to generate all possible triangles by selecting 3 points from the input array. For each combination, calculate the triangle area using the cross product formula: `|x1(y2-y3) + x2(y3-y1) + x3(y1-y2)| / 2`. Keep track of the maximum area found and return it.
8+
9+
# Complexity
10+
- Time complexity: $$O(n^3)$$
11+
- Space complexity: $$O(1)$$
12+
13+
# Code
14+
```typescript
15+
const largestTriangleArea = (points: number[][]): number => {
16+
const totalPoints = points.length;
17+
let maxTriangleArea = 0;
18+
19+
const calculateTriangleArea = (point1: number[], point2: number[], point3: number[]): number => {
20+
return Math.abs(
21+
point1[0] * (point2[1] - point3[1]) +
22+
point2[0] * (point3[1] - point1[1]) +
23+
point3[0] * (point1[1] - point2[1])
24+
) / 2;
25+
};
26+
27+
for (let firstIndex = 0; firstIndex < totalPoints; firstIndex++) {
28+
for (let secondIndex = firstIndex + 1; secondIndex < totalPoints; secondIndex++) {
29+
for (let thirdIndex = secondIndex + 1; thirdIndex < totalPoints; thirdIndex++) {
30+
const currentTriangleArea = calculateTriangleArea(
31+
points[firstIndex],
32+
points[secondIndex],
33+
points[thirdIndex]
34+
);
35+
maxTriangleArea = Math.max(maxTriangleArea, currentTriangleArea);
36+
}
37+
}
38+
}
39+
40+
return maxTriangleArea;
41+
};
42+
```

0 commit comments

Comments
 (0)