LeetCode 0812. Largest Triangle Area Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0812. Largest Triangle Area

Description

Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.

Example 2:

Input: points = [[1,0],[0,0],[0,1]]
Output: 0.50000

 

Constraints:

  • 3 <= points.length <= 50
  • -50 <= xi, yi <= 50
  • All the given points are unique.

Solutions

Solution: Enumerate Triangle Area Formula

Given three points (x_1, y_1), (x_2, y_2), (x_3, y_3) on a plane, the area formula is:

$S = 12 | x_1y_2 + x_2y_3 + x_3y_1 - x_1y_3 - x_2y_1 - x_3y_2 |$

We can enumerate all combinations of three points and calculate the maximum area.

The time complexity is O(n^3), where n is the number of points. The space complexity is O(1).

PythonJavaC++GoTypeScriptRust
class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: ans = 0 for x1, y1 in points: for x2, y2 in points: for x3, y3 in points: u1, v1 = x2 - x1, y2 - y1 u2, v2 = x3 - x1, y3 - y1 t = abs(u1 * v2 - u2 * v1) / 2 ans = max(ans, t) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !