题目描述
上面这个博客把问题描述的很清楚。
JAVA代码:
public class 可见山峰对问题 {
public static class Pair {
public int value;
public int times;
public Pair(int value) {
this.value = value;
this.times = 1;
}
}
public static long communication(int[] arr) {
if (arr == null || arr.length <2) {
return 0;
}
int len = arr.length;
int maxIndex = 0;
for (int i = 0; i < len; i++) {
maxIndex = arr[i] > arr[maxIndex] ? i : maxIndex;
}
int value = arr[maxIndex];
long res = 0L;
int index = nextIndex(len, maxIndex);
Stack<Pair> stack = new Stack<Pair>();
stack.push(new Pair(value));
while (index != maxIndex) {
value = arr[index];
while (!stack.isEmpty() && value > stack.peek().value) {
int times = stack.pop().times;
res += getInternalSum(times) + (times * 2);
}
if(stack.peek().value==value)
{
stack.peek().times++;
}else {
stack.push(new Pair(value));
}
index = nextIndex(len, index);
}
while (!stack.isEmpty()) {
int times = stack.pop().times;
res += getInternalSum(times);
if (!stack.isEmpty()) {
res += times;
if (stack.size() > 1) {
res += times;
} else {
res += stack.peek().times > 1 ? times : 0L;
}
}
}
return res;
}
// Cn2
public static long getInternalSum(int n) {
return n == 1L ? 0L : (long)(n - 1) * (long)n / 2L;
}
// 形成环
public static int nextIndex(int len, int i) {
return i < (len - 1) ? (i + 1) : 0;
}
public static void main(String[] args) {
int[] arr= {1,2,4,5,3};
long res = communication(arr);
System.out.println(res);
}
}