Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 23, 2018 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/dcc26dc418639aa9942efe2bc9e8a682 to your computer and use it in GitHub Desktop.
Save jianminchen/dcc26dc418639aa9942efe2bc9e8a682 to your computer and use it in GitHub Desktop.
Leetcode 42: Trap rain water - first online submission passing online judge. There are two issues, first one is to learn how to call Array.Reverse(), second one is to add 49 if condition.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrapRainingWater
{
/// <summary>
/// Leetcode 42: Trapping raining water
/// https://leetcode.com/problems/trapping-rain-water/description/
/// preprocessing the array to store prefix maximum and suffix maximum.
/// Time complexity is O(N) where N is the length of the array
/// </summary>
class Program
{
static void Main(string[] args)
{
var test = Trap(new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 });
Debug.Assert(test == 6);
}
public static int Trap(int[] height)
{
if (height == null || height.Length == 0)
{
return 0;
}
var length = height.Length;
// scan left to right to get maximum of prefix
var prefixMax = ScanLeftToRightPrefixMax(height);
// scan right to left to get maximum of postfix
Array.Reverse(height);
var suffixMax = ScanLeftToRightPrefixMax(height);
Array.Reverse(height);
Array.Reverse(suffixMax);
// add the sum of the difference for each bar
var maxSum = 0;
for (int index = 0; index < length; index++)
{
var smallOne = Math.Min(prefixMax[index], suffixMax[index]);
var current = height[index];
if (smallOne > current)
{
maxSum += smallOne - current;
}
}
return maxSum;
}
private static int[] ScanLeftToRightPrefixMax(int[] height)
{
var length = height.Length;
var prefixMax = new int[length];
var maxValue = height[0];
prefixMax[0] = height[0];
for (int index = 1; index < length; index++)
{
var visit = height[index - 1];
maxValue = visit > maxValue ? visit : maxValue;
prefixMax[index] = maxValue;
}
return prefixMax;
}
}
}
@jianminchen
Copy link
Author

May 23, 2018
There are three issues to fix in order to pass online judge. First one is to check base condition, check array length is 0 on line 26; second one is to apply Array.Reverse API, it has been called three times. And the last one is to add if condition statement on line 49.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment