Skip to content

Commit

Permalink
✨ 42. Trapping Rain Water
Browse files Browse the repository at this point in the history
  • Loading branch information
DremyGit authored and 宏逸 committed May 28, 2023
1 parent 7c302a7 commit c34a847
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
31 changes: 17 additions & 14 deletions src/trapping-rain-water/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,39 @@
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
const leftMaxList = getMaxList(height, 1)
const rightMaxList = getMaxList(height, -1)
const sum = height.reduce((total, h, index) => total += getWater(h, leftMaxList[index], rightMaxList[index]), 0)
let trap = function(height) {
const leftMaxList = getMaxList(height, 1);
const rightMaxList = getMaxList(height, -1);
const sum = height.reduce(
(total, h, index) =>
(total += getWater(h, leftMaxList[index], rightMaxList[index])),
0
);
return sum;
};


const getMaxList = (_height, position) => {
const height = _height.slice();
if (position < 0) {
height.reverse();
height.reverse();
}
const list = [height[0]];
for (let i = 1, len = height.length; i < len; i++) {
if (height[i] > list[i - 1]) {
list[i] = height[i]
} else {
list[i] = list[i - 1]
}
if (height[i] > list[i - 1]) {
list[i] = height[i];
} else {
list[i] = list[i - 1];
}
}
if (position < 0) {
list.reverse();
list.reverse();
}
return list;
}
};

const getWater = (h, leftMax, rightMax) => {
const value = Math.max(Math.min(leftMax, rightMax) - h, 0);
return value;
}
};

export default trap;
4 changes: 2 additions & 2 deletions src/trapping-rain-water/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import trap from './';

describe('42. Trapping Rain Water:', () => {
test('Example 1', () => {
expect(trap([0,1,0,2,1,0,1,3,2,1,2,1])).toBe(6);
expect(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])).toBe(6);
});
test('Example 2', () => {
expect(trap([4,2,0,3,2,5])).toBe(9);
expect(trap([4, 2, 0, 3, 2, 5])).toBe(9);
});
});

0 comments on commit c34a847

Please sign in to comment.