Skip to content

533 - Trapping Rain Water - javascript #535

@jsartisan

Description

@jsartisan

index.js

/**
 * @param {number[]} height
 * @return {number}
 */
export function trap(height) {
  let n = height.length;
  let leftMax = []
  let rightMax = [];

  leftMax[0] = height[0];

  for (let i = 1; i < n; i++) {
    leftMax[i] = Math.max(leftMax[i - 1], height[i]);
  }

  rightMax[n - 1] = height[n - 1];

  for (let i = n - 2; i >= 0; i--) {
    rightMax[i] = Math.max(rightMax[i+1], height[i])
  }


  let sum = 0;

  for (let i = 0; i < height.length; i++) {
    sum += Math.min(leftMax[i], rightMax[i]) - height[i];
  }

  return sum;
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions