Skip to content

Instantly share code, notes, and snippets.

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/0e2e1a46d595e768bfabef2a6d7239ee to your computer and use it in GitHub Desktop.
Save jianminchen/0e2e1a46d595e768bfabef2a6d7239ee to your computer and use it in GitHub Desktop.
Write a C# solution using stack, the code is written based on the java code - segmentfault blog.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode84_LargestRectangleHistogram
{
/// <summary>
/// Leetcode 84 - largest rectangle histogram
/// code practice is based on the coding blog:
/// https://gist.github.com/jianminchen/74f27e22b520c6074c1fbc6e5c45d9a4
///
/// </summary>
class Program
{
static void Main(string[] args)
{
RunTestcase();
}
public static void RunTestcase()
{
var area = CalculateLargestRectangleArea(new int[]{2, 1, 5, 6, 2, 3});
Debug.Assert(area == 10);
}
/// <summary>
/// greedy algorithm to calculate the largest rectangle histogram
///
/// </summary>
/// <param name="height"></param>
/// <returns></returns>
public static int CalculateLargestRectangleArea(int[] height) // [2, 1, 5, 6, 2, 3]
{
var stack = new Stack<int>();
var index = 0;
var largestArea = 0;
int length = height.Length; // 6
while (index < length) // true; index = 1; index = 2;
{
// stack empty going upward
if (stack.Count == 0 || height[stack.Peek()] < height[index]) // index = 1, false;
{
stack.Push(index++); // 0, index = 1;
}
else
{
// going downward and then pop stack, calculate rectangle.
popStackAndCalculate(ref largestArea, stack, height, index);
}
}
while (stack.Count > 0)
{
popStackAndCalculate(ref largestArea, stack, height, length);
}
return largestArea;
}
/// <summary>
/// downward and then pop stack to calculate the rectangle
/// </summary>
/// <param name="largestArea"></param>
/// <param name="stack"></param>
/// <param name="height"></param>
private static void popStackAndCalculate(ref int largestArea, Stack<int> stack, int[] height, int rightIndex)
{
int length = height.Length; // 6
int lastHeight = height[stack.Pop()]; // 2
int width = stack.Count == 0 ? rightIndex : rightIndex - stack.Peek() - 1; // 1
largestArea = Math.Max(largestArea, lastHeight * width); // 2 * 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment