Leetcode 812. Largest Triangle Area
Given a list of points on the 2D plane, you should compute the area of the largest triangle that can be formed by any 3 of the provided points.
You are given an array of points points
where points[i] = [xi, yi]
come in pairs representing the coordinates of points on a 2D plane.
Return the area of the largest triangle that can be formed.
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
public:
double largestTriangleArea(vector<vector<int>>& points) {
int n = points.size();
double maxArea = 0.0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
double area = 0.5 * fabs(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]));
maxArea = max(maxArea, area);
}
}
}
return maxArea;
}
};
This solution iterates through each combination of three points, calculates the triangle area for each combination, and keeps track of the maximum area encountered. Given the constraints, this approach should perform well.
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?