All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0801_0900.s0812_largest_triangle_area.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0801_0900.s0812_largest_triangle_area;

// #Easy #Array #Math #Geometry #2022_03_23_Time_5_ms_(92.04%)_Space_39.8_MB_(87.61%)

/**
 * 812 - Largest Triangle Area\.
 *
 * Easy
 *
 * 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:**
 *
 * ![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/04/1027.png)
 *
 * **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**.
**/
public class Solution {
    public double largestTriangleArea(int[][] points) {
        int n = points.length;
        double max = 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;
                    int[] a = points[i];
                    int[] b = points[j];
                    int[] c = points[k];
                    area = Math.abs(area(a, b) + area(b, c) + area(c, a));
                    if (area > max) {
                        max = area;
                    }
                }
            }
        }
        return max;
    }

    private double area(int[] a, int[] b) {
        int l = b[0] - a[0];
        double h = (a[1] + b[1] + 200) / 2.0;
        return l * h;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy