You are given a 0-indexed 2D integer array peaks where peaks[i] = [xi, yi] states that mountain i has a peak at coordinates (xi, yi). A mountain can be described as a right-angled isosceles triangle, with its base along the
x-axis and a right angle at its peak. More formally, the gradients of ascending and descending the mountain are 1 and -1 respectively.
A mountain is considered visible if its peak does not lie within another mountain (including the border of other mountains).

Input: peaks =[[2,2],[6,3],[5,4]]Output: 2Explanation: The diagram above shows the mountains.- Mountain 0is visible since its peak does not lie within another mountain or its sides.- Mountain 1is not visible since its peak lies within the side of mountain 2.- Mountain 2is visible since its peak does not lie within another mountain or its sides.There are 2 mountains that are visible.
Example 2:
1
2
3
4
5

Input: peaks =[[1,3],[1,3]]Output: 0Explanation: The diagram above shows the mountains(they completely overlap).Both mountains are not visible since their peaks lie within each other.
Each mountain covers an interval [x - y, x + y]. If a mountain’s interval is completely covered by another, its peak is not visible. By sorting intervals and scanning greedily, we can efficiently count visible mountains.
import java.util.*;
classSolution {
publicintvisibleMountains(int[][] peaks) {
int n = peaks.length;
int[][] segs =newint[n][2];
for (int i = 0; i < n; i++) {
segs[i][0]= peaks[i][0]- peaks[i][1];
segs[i][1]= peaks[i][0]+ peaks[i][1];
}
Arrays.sort(segs, (a, b) -> a[0]!= b[0]? a[0]- b[0] : b[1]- a[1]);
int ans = 0, maxr =-1;
for (int i = 0; i < n; i++) {
if (i+1 < n && segs[i][0]== segs[i+1][0]&& segs[i][1]== segs[i+1][1]) continue;
if (segs[i][1]> maxr) {
ans++;
maxr = segs[i][1];
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funvisibleMountains(peaks: Array<IntArray>): Int {
val segs = peaks.map { intArrayOf(it[0] - it[1], it[0] + it[1]) }.toTypedArray()
segs.sortWith(compareBy({ it[0] }, { -it[1] }))
var ans = 0var maxr = -1for (i in segs.indices) {
if (i+1 < segs.size && segs[i][0] == segs[i+1][0] && segs[i][1] == segs[i+1][1]) continueif (segs[i][1] > maxr) {
ans++ maxr = segs[i][1]
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defvisibleMountains(self, peaks: list[list[int]]) -> int:
segs = sorted([(x-y, x+y) for x, y in peaks], key=lambda p: (p[0], -p[1]))
ans, maxr, n =0, -1, len(segs)
i =0while i < n:
j = i
while j+1< n and segs[j+1] == segs[i]:
j +=1if segs[i][1] > maxr:
ans +=1 maxr = segs[i][1]
i = j +1return ans