diff --git a/src/LeetCode.Solutions/NeetCode150/ArraysAndHashing/TrappingRainWaterSolution.cs b/src/LeetCode.Solutions/NeetCode150/ArraysAndHashing/TrappingRainWaterSolution.cs new file mode 100644 index 0000000..3f19159 --- /dev/null +++ b/src/LeetCode.Solutions/NeetCode150/ArraysAndHashing/TrappingRainWaterSolution.cs @@ -0,0 +1,44 @@ +namespace LeetCode.Solutions.NeetCode150.ArraysAndHashing; +/// +// You are given an array non-negative integers heights which represent an elevation map. Each value heights[i] represents the height of a bar, which has a width of 1. + +// Return the maximum area of water that can be trapped between the bars. +/// +[Level(Level.Hard)] +public class TrappingRainWaterSolution +{ + [TimeComplexity("O(n)")] + [SpaceComplexity("O(1)")] + public int Trap(int[] height) + { + + if (height == null || height.Length == 0) + { + return 0; + } + + int left = 0; + int right = height.Length - 1; + + int leftMax = height[left]; + int rightMax = height[right]; + int result = 0; + + while (left < right) + { + if (leftMax < rightMax) + { + left++; + leftMax = Math.Max(leftMax, height[left]); + result += leftMax - height[left]; + } + else + { + right--; + rightMax = Math.Max(rightMax, height[right]); + result += rightMax - height[right]; + } + } + return result; + } +} \ No newline at end of file diff --git a/src/LeetCode.Tests/NeetCode150/TwoPointers/TrappingRainWaterTests.cs b/src/LeetCode.Tests/NeetCode150/TwoPointers/TrappingRainWaterTests.cs new file mode 100644 index 0000000..2c9c592 --- /dev/null +++ b/src/LeetCode.Tests/NeetCode150/TwoPointers/TrappingRainWaterTests.cs @@ -0,0 +1,42 @@ +using LeetCode.Solutions.NeetCode150.ArraysAndHashing; + +namespace LeetCode.Tests.NeetCode150.TwoPointers; + +public class TrappingRainWaterTests +{ + [Test] + public void Case1() + { + var solution = new TrappingRainWaterSolution(); + var result = solution.Trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]); + + result.Should().Be(6); + } + + [Test] + public void Case2() + { + var solution = new TrappingRainWaterSolution(); + var result = solution.Trap([4, 2, 0, 3, 2, 5]); + + result.Should().Be(9); + } + + [Test] + public void Case3() + { + var solution = new TrappingRainWaterSolution(); + var result = solution.Trap([1, 2, 3, 4, 5]); + + result.Should().Be(0); + } + + [Test] + public void Case4() + { + var solution = new TrappingRainWaterSolution(); + var result = solution.Trap([5, 4, 3, 2, 1]); + + result.Should().Be(0); + } +} \ No newline at end of file