Last active
October 31, 2016 19:04
-
-
Save sleemer/29eb8360eae2c3991392303e6ada7133 to your computer and use it in GitHub Desktop.
C# implementation of algorithm of calculation LargestRectangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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