|
| 1 | +package g3501_3600.s3588_find_maximum_area_of_a_triangle; |
| 2 | + |
| 3 | +// #Medium #Array #Hash_Table #Math #Greedy #Enumeration #Geometry |
| 4 | +// #2025_06_23_Time_410_ms_(100.00%)_Space_165.98_MB_(100.00%) |
| 5 | + |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.TreeSet; |
| 9 | + |
| 10 | +public class Solution { |
| 11 | + public long maxArea(int[][] coords) { |
| 12 | + Map<Integer, TreeSet<Integer>> xMap = new HashMap<>(); |
| 13 | + Map<Integer, TreeSet<Integer>> yMap = new HashMap<>(); |
| 14 | + TreeSet<Integer> allX = new TreeSet<>(); |
| 15 | + TreeSet<Integer> allY = new TreeSet<>(); |
| 16 | + for (int[] coord : coords) { |
| 17 | + int x = coord[0]; |
| 18 | + int y = coord[1]; |
| 19 | + xMap.computeIfAbsent(x, k -> new TreeSet<>()).add(y); |
| 20 | + yMap.computeIfAbsent(y, k -> new TreeSet<>()).add(x); |
| 21 | + allX.add(x); |
| 22 | + allY.add(y); |
| 23 | + } |
| 24 | + long ans = Long.MIN_VALUE; |
| 25 | + for (Map.Entry<Integer, TreeSet<Integer>> entry : xMap.entrySet()) { |
| 26 | + int x = entry.getKey(); |
| 27 | + TreeSet<Integer> ySet = entry.getValue(); |
| 28 | + if (ySet.size() < 2) { |
| 29 | + continue; |
| 30 | + } |
| 31 | + int minY = ySet.first(); |
| 32 | + int maxY = ySet.last(); |
| 33 | + int base = maxY - minY; |
| 34 | + int minX = allX.first(); |
| 35 | + int maxX = allX.last(); |
| 36 | + if (minX != x) { |
| 37 | + ans = Math.max(ans, (long) Math.abs(x - minX) * base); |
| 38 | + } |
| 39 | + if (maxX != x) { |
| 40 | + ans = Math.max(ans, (long) Math.abs(x - maxX) * base); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + for (Map.Entry<Integer, TreeSet<Integer>> entry : yMap.entrySet()) { |
| 45 | + int y = entry.getKey(); |
| 46 | + TreeSet<Integer> xSet = entry.getValue(); |
| 47 | + if (xSet.size() < 2) { |
| 48 | + continue; |
| 49 | + } |
| 50 | + int minX = xSet.first(); |
| 51 | + int maxX = xSet.last(); |
| 52 | + int base = maxX - minX; |
| 53 | + int minY = allY.first(); |
| 54 | + int maxY = allY.last(); |
| 55 | + if (minY != y) { |
| 56 | + ans = Math.max(ans, (long) Math.abs(y - minY) * base); |
| 57 | + } |
| 58 | + if (maxY != y) { |
| 59 | + ans = Math.max(ans, (long) Math.abs(y - maxY) * base); |
| 60 | + } |
| 61 | + } |
| 62 | + return ans == Long.MIN_VALUE ? -1 : ans; |
| 63 | + } |
| 64 | +} |
0 commit comments