Skip to content

Instantly share code, notes, and snippets.

@sleemer
Last active October 31, 2016 19:04
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 sleemer/29eb8360eae2c3991392303e6ada7133 to your computer and use it in GitHub Desktop.
Save sleemer/29eb8360eae2c3991392303e6ada7133 to your computer and use it in GitHub Desktop.
C# implementation of algorithm of calculation LargestRectangle
/// Description of the problem can be found at https://www.hackerrank.com/challenges/largest-rectangle/editorial
/// As a real use case we could consider usage of this algorithm to find out the largest rectangular subarray containing only ones.
/// For more details go to http://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529
public int LargestRectangle(string input)
{
var heights = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.Concat(new[] { 0 }) // add tail 0 to force calculation when we reach the last element
.ToArray();
var positions = new Stack<int>();
var largest = 0;
for (int i = 0; i < heights.Length; i++)
{
while (positions.Count > 0 && heights[positions.Peek()] > heights[i])
{
int height = heights[positions.Pop()];
int width = positions.Count == 0 ? i : i - positions.Peek() - 1;
largest = Math.Max(largest, height * width);
}
positions.Push(i);
}
return largest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment