Leetcode 812. Largest Triangle Area
Given a list of points in the 2D plane, find the area of the largest triangle that can be formed by any three of the points.
You may assume that all the points lie within the range [-50, 50] and all coordinates are integers.
Your answer should be within 10^-6
of the true answer.
[x, y]
.10^-6
of the true answer.n
) will be between 3 and 50 inclusive.Here is the implementation in Java:
public class Solution {
public double largestTriangleArea(int[][] points) {
int n = points.length;
double maxArea = 0.0;
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
double area = calculateArea(points[i], points[j], points[k]);
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
}
private double calculateArea(int[] p1, int[] p2, int[] p3) {
// Using the Shoelace formula to calculate area of a triangle
return 0.5 * Math.abs(p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]));
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] points = \ use example from above
System.out.println(sol.largestTriangleArea(points)); // Output should be 2.0
}
}
The time complexity for this solution is (O(n^3)), where (n) is the number of points. This is because we are considering all combinations of three points from the list, which is (\binom{n}{3} \approx \frac{n^3}{6}).
The space complexity is (O(1)) beyond the input storage, as we are using only a few extra variables to store computed areas and the maximum area value.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?