Skip to content

Commit ea950e4

Browse files
committed
Added TrappingRainWater solution
1 parent 1139e82 commit ea950e4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

CodingInterview/CodingInterview/Tests.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using NUnit.Framework;
2+
using System;
23
using System.Collections.Generic;
34
using System.Linq;
45

@@ -66,6 +67,24 @@ int[] MoveZeros(int[] arrayOfNumbers)
6667
return listOfElements.ToArray();
6768
}
6869

70+
int GetTrappingRainWater(int[] elevationMap)
71+
{
72+
if (elevationMap == null || elevationMap.Length == 0)
73+
return 0;
74+
int waterToDrop = 0;
75+
int level = 0;
76+
int left = 0;
77+
int right = elevationMap.Length - 1;
78+
while(left < right)
79+
{
80+
int lower = elevationMap[elevationMap[left] < elevationMap[right] ? left++ : right--];
81+
level = Math.Max(lower, level);
82+
waterToDrop += level - lower;
83+
Console.WriteLine($"left{left} right{right} lower {lower} level {level} waterToDrop {waterToDrop}");
84+
}
85+
return waterToDrop;
86+
}
87+
6988
[Test]
7089
public void RemoveDuplicatesFromSortedArray_1()
7190
{
@@ -110,5 +129,16 @@ public void MoveZeros_4()
110129

111130
Assert.AreEqual(expectedArrayWithZerosInTheEnd, arrayWithRemoveElement);
112131
}
132+
133+
[Test]
134+
public void TrappingRainWater_6()
135+
{
136+
var elevationMap = new int[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
137+
var expectedValue = 6;
138+
139+
var rainWaterValue = GetTrappingRainWater(elevationMap);
140+
141+
Assert.AreEqual(expectedValue, rainWaterValue);
142+
}
113143
}
114144
}

0 commit comments

Comments
 (0)