-
Notifications
You must be signed in to change notification settings - Fork 35
/
LargestRectangle.cs
106 lines (82 loc) · 2.63 KB
/
LargestRectangle.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Largest Rectangle
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Solution {
// Complete the largestRectangle function below.
class Data{
public readonly int Index;
public readonly int Size;
public Data(int index, int size){
Index = index;
Size = size;
}
}
// Complete the largestRectangle function below.
static long largestRectangle(int[] h)
{
var max = 0L;
var stack = new Stack<Data>();
for (var index = 0; index < h.Length; index++)
{
if (!TryPeek(stack, out var value) || value.Size < h[index])
stack.Push(new Data(index, h[index]));
else if (value.Size > h[index])
{
var lastBlockIndex = 0;
do
{
max = Math.Max(max,
value.Size * (index - value.Index));
lastBlockIndex = value.Index;
stack.Pop();
TryPeek(stack, out value);
} while (value != null && value.Size > h[index]);
if(value == null)
stack.Push(new Data(0, h[index]));
else if(value.Size < h[index])
stack.Push(new Data(lastBlockIndex, h[index]));
}
}
while (TryPop(stack, out var val))
{
max = Math.Max(max,
val.Size * (h.Length - val.Index));
}
return max;
}
static bool TryPeek(Stack<Data> stack, out Data value)
{
value = null;
if (stack.Count == 0) return false;
value = stack.Peek();
return true;
}
static bool TryPop(Stack<Data> stack, out Data value)
{
value = null;
if (stack.Count == 0) return false;
value = stack.Pop();
return true;
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int n = Convert.ToInt32(Console.ReadLine());
int[] h = Array.ConvertAll(Console.ReadLine().Split(' '), hTemp => Convert.ToInt32(hTemp))
;
long result = largestRectangle(h);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}