0
点赞
收藏
分享

微信扫一扫

NC128 接雨水问题

荷一居茶生活 2022-03-21 阅读 57
C++

描述

给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个柱子高度图,计算按此排列的柱子,下雨之后能接多少雨水。(数组以外的区域高度视为0)

class Solution {
public:
	/**
	* max water
	* @param arr int整型vector the array
	* @return long长整型
	*/
	long long maxWater(vector<int>& arr) {
		int ans = 0;
		int left = 0;
		int right = arr.size() - 1;
		int leftMax = 0;
		int rightMax = 0;
		while (left < right)
		{
			leftMax = max(leftMax, arr[left]);
			rightMax = max(rightMax, arr[right]);
			if (leftMax < rightMax)
			{
				ans += leftMax - arr[left];
				++left;
			}
			else
			{
				ans += rightMax - arr[right];
				--right;
			}

		}
		return ans;
	}
};

 

举报

相关推荐

0 条评论