812. Largest Triangle Area #2222
-
Topics: Given an array of points on the X-Y plane points where Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the largest triangle area that can be formed by any three distinct points from a given list of points on the X-Y plane. The solution involves checking all possible triplets of points and calculating the area of the triangle they form using a mathematical formula. The key is to efficiently compute the area for each triplet and keep track of the maximum area found. Approach
Let's implement this solution in PHP: 812. Largest Triangle Area <?php
/**
* @param Integer[][] $points
* @return Float
*/
function largestTriangleArea($points) {
$maxArea = 0;
$n = count($points);
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
for ($k = $j + 1; $k < $n; $k++) {
$x1 = $points[$i][0];
$y1 = $points[$i][1];
$x2 = $points[$j][0];
$y2 = $points[$j][1];
$x3 = $points[$k][0];
$y3 = $points[$k][1];
$area = 0.5 * abs($x1 * ($y2 - $y3) + $x2 * ($y3 - $y1) + $x3 * ($y1 - $y2));
if ($area > $maxArea) {
$maxArea = $area;
}
}
}
}
return $maxArea;
}
// Test cases
$points1 = [[0,0],[0,1],[1,0],[0,2],[2,0]];
echo largestTriangleArea($points1) . "\n"; // Output: 2.0
$points2 = [[1,0],[0,0],[0,1]];
echo largestTriangleArea($points2) . "\n"; // Output: 0.5
?> Explanation:
This approach efficiently checks all possible triangles by leveraging the mathematical formula for area calculation, ensuring correctness while maintaining simplicity due to the constraints on the number of points. The complexity is O(n³), which is feasible given the maximum input size of 50 points. |
Beta Was this translation helpful? Give feedback.
We need to find the largest triangle area that can be formed by any three distinct points from a given list of points on the X-Y plane. The solution involves checking all possible triplets of points and calculating the area of the triangle they form using a mathematical formula. The key is to efficiently compute the area for each triplet and keep track of the maximum area found.
Approach