Skip to content

Commit

Permalink
add Trapping Rain Water Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ianoflynnautomation committed Oct 20, 2024
1 parent 4466bbb commit 35fb957
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace LeetCode.Solutions.NeetCode150.ArraysAndHashing;
/// <summary>
// 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.
/// </summary>
[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;
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}

0 comments on commit 35fb957

Please sign in to comment.