Trapping Rain Water
JavaScript
Hard
6 views
Problem Description
Given heights array, find how much water can be trapped after rain.
Input Format
One line: n then n integers.
Output Format
One integer water units.
Sample Test Case
Input:
12 0 1 0 2 1 0 1 3 2 1 2 1
Official Solution
const fs=require('fs');const a=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!a[0])process.exit(0);let i=0;const n=Number(a[i++]);let h=new Array(n);for(let j=0;j<n;j++)h[j]=Number(a[i++]);let l=0,r=n-1,lm=0,rm=0;let w=0n;while(l<=r){if(h[l]<=h[r]){if(h[l]>=lm)lm=h[l];else w+=BigInt(lm-h[l]);l++;}else{if(h[r]>=rm)rm=h[r];else w+=BigInt(rm-h[r]);r--;}}process.stdout.write(w.toString());
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!