单调栈应用——可见山峰对问题

题目描述
上面这个博客把问题描述的很清楚。
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);
	}	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值