#812

Largest Triangle Area

Easy
ArrayMathGeometryBrute ForceGeometry
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The brute force approach checks all combinations, which is inefficient. However, we can use the same formula for area calculation but optimize our selection of points to avoid unnecessary calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to store the maximum area found.
  2. 2Step 2: Iterate through all combinations of three different points using a single loop.
  3. 3Step 3: Calculate the area using the same formula as before.
  4. 4Step 4: Update the maximum area if the calculated area is larger.
  5. 5Step 5: Return the maximum area found.
solution.py9 lines
1def largestTriangleArea(points):
2    max_area = 0
3    n = len(points)
4    for i in range(n):
5        for j in range(i + 1, n):
6            for k in range(j + 1, n):
7                area = 0.5 * abs(points[i][0] * (points[j][1] - points[k][1]) + points[j][0] * (points[k][1] - points[i][1]) + points[k][0] * (points[i][1] - points[j][1]))
8                max_area = max(max_area, area)
9    return max_area

Complexity note: The time complexity remains O(n²) because we still need to check all combinations of three points. The space complexity is O(1) as we only use a few variables for calculations.

  • 1The area of a triangle can be calculated using the determinant formula.
  • 2The maximum area triangle can be formed by selecting the right combination of points.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.