[42] 接雨水

/**
 * @param {number[]} height
 * @return {number}
 */
const trap = function (height) {
  let res = 0, left = 0, right = height.length - 1, lmax = 0, rmax = 0
  while (left <= right) {
    lmax = Math.max(lmax, height[left])
    rmax = Math.max(rmax, height[right])
    if (lmax < rmax) {
      res = res + (lmax - height[left])
      left++
    } else {
      res = res + (rmax - height[right])
      right--
    }
  }
  return res
};

 

posted @ 2023-11-30 13:53  人恒过  阅读(14)  评论(0)    收藏  举报