Cover image for LeetCode Daily Challenge P812 Largest Triangle Area

LeetCode Daily Challenge P812 Largest Triangle Area


Timeline

Timeline

2025-09-27

init

Brute force

Problem:

No need to overthink this problem; it mainly tests geometry knowledge, so just enumerate all possibilities.
The formula for calculating the area of a triangle is:

S=12x1(y2y3)+x2(y3y1)+x3(y1y2)S = \frac{1}{2} \left| x_1(y_2 - y_3) + x_2(y_3 - y_1) + x_3(y_1 - y_2) \right|

Assume these three points: the first point i is on the left side of the points array, the second point is located between the two points in the array, and the third point is on the right.

1234567891011121314151617181920212223242526272829303132333435363738
#include <cmath>#include <vector>using std::vector;class Solution {public:  double largestTriangleArea(vector<vector<int>> &points) {    int n;    int x1, x2, x3;    int y1, y2, y3;    double max_area = 0;    double area;    n = points.size();    for (int i = 0; i < n; i++) {      for (int j = i + 1; j < n; j++) {        for (int k = j + 1; k < n; k++) {          x1 = points[i][0];          x2 = points[j][0];          x3 = points[k][0];          y1 = points[i][1];          y2 = points[j][1];          y3 = points[k][1];          area =              0.5 * std::fabs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));          if (area > max_area) {            max_area = area;          }        }      }    }    return max_area;  }};
Loading comments…