Skip to content

Commit fc795c3

Browse files
authored
Create 0812-largest-triangle-area.java
1 parent b0634df commit fc795c3

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Question: Largest Triangle Area
3+
Link: https://leetcode.com/problems/largest-triangle-area/
4+
5+
Question Info:
6+
You are given an array of points on a 2D plane. Each point is represented as an integer coordinate [x, y].
7+
Your task is to return the largest area of a triangle formed by any three points in the given array.
8+
9+
Approach:
10+
1. Use the shoelace formula (determinant method) to compute the area of a triangle formed by three points (x1,y1), (x2,y2), (x3,y3).
11+
Formula:
12+
Area = 0.5 * |x1(y2 − y3) + x2(y3 − y1) + x3(y1 − y2)|
13+
2. Iterate over all possible triplets of points using three nested loops.
14+
3. For each triplet, calculate the area using the formula and update the maximum area found.
15+
4. Return the maximum area.
16+
17+
Dry Run:
18+
Example: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
19+
20+
- Pick (0,0), (0,1), (1,0) → Area = 0.5
21+
- Pick (0,0), (0,2), (2,0) → Area = 2
22+
- Pick (0,1), (0,2), (2,0) → Area = 1
23+
- After checking all triplets, maximum = 2
24+
25+
Time Complexity: O(n^3), since we check all triplets of points.
26+
Space Complexity: O(1), only a few variables used.
27+
*/
28+
29+
class Solution {
30+
public double largestTriangleArea(int[][] points) {
31+
int length = points.length;
32+
double maxArea = Double.MIN_VALUE;
33+
34+
for (int i = 0; i < length - 2; i++) {
35+
for (int j = i + 1; j < length - 1; j++) {
36+
for (int k = j + 1; k < length; k++) {
37+
38+
int x1 = points[i][0], y1 = points[i][1];
39+
int x2 = points[j][0], y2 = points[j][1];
40+
int x3 = points[k][0], y3 = points[k][1];
41+
42+
double area = 0.5 * Math.abs(
43+
x1 * (y2 - y3) +
44+
x2 * (y3 - y1) +
45+
x3 * (y1 - y2));
46+
47+
maxArea = Math.max(maxArea, area);
48+
}
49+
}
50+
}
51+
return maxArea;
52+
}
53+
}

0 commit comments

Comments
 (0)