You are given an array of points on the XY-plane where points[i] = [xi, yi]. Each point is represented as an integer coordinate [xi, yi].
Return the area of the largest triangle that can be formed by any three different points. Answers within 10^-5 of the true value will be accepted.
3 <= points.length <= 50points[i].length == 2-50 <= points[i][0], points[i][1] <= 50Use the shoelace formula with brute force enumeration to find the largest triangle area among all possible triplets of points.
The shoelace formula calculates the area of a polygon given its vertices. For three points (x1,y1), (x2,y2), (x3,y3), the area is:
Area = 0.5 * |x1(y2 − y3) + x2(y3 − y1) + x3(y1 − y2)|
Algorithm:
This approach works because:
Example Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Step-by-step execution:
Triplet (0,0), (0,1), (1,0):
| Area = 0.5 * | 0(1-0) + 0(0-0) + 1*(0-1) | = 0.5 * | 0 + 0 + 1*(-1) | = 0.5 * 1 = 0.5 |
Triplet (0,0), (0,2), (2,0):
| Area = 0.5 * | 0(2-0) + 0(0-0) + 2*(0-2) | = 0.5 * | 0 + 0 + 2*(-2) | = 0.5 * 4 = 2.0 |
Triplet (0,1), (0,2), (2,0):
| Area = 0.5 * | 0(2-0) + 0(0-1) + 2*(1-2) | = 0.5 * | 0 + 0 + 2*(-1) | = 0.5 * 2 = 1.0 |
Other triplets give smaller areas…
Maximum area found = 2.0
class Solution {
public double largestTriangleArea(int[][] points) {
int length = points.length;
double maxArea = Double.MIN_VALUE;
for (int i = 0; i < length - 2; i++) {
for (int j = i + 1; j < length - 1; j++) {
for (int k = j + 1; k < length; k++) {
int x1 = points[i][0], y1 = points[i][1];
int x2 = points[j][0], y2 = points[j][1];
int x3 = points[k][0], y3 = points[k][1];
double area = 0.5 * Math.abs(
x1 * (y2 - y3) +
x2 * (y3 - y1) +
x3 * (y1 - y2));
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
}
}
For larger constraints, we could use:
Time Complexity: O(n log n) - much more efficient for large n Space Complexity: O(n) - for storing convex hull
For very large point sets:
Time Complexity: O(k) - where k is number of samples Space Complexity: O(1) - constant space