-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem4.cs
107 lines (87 loc) · 3.1 KB
/
Problem4.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
107
using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment5
{
class Problem4
{
public static void RunInteractiveTesting()
{
string intro =
"==============\n" +
"= Problem #4 =\n" +
"==============\n" +
"\n" +
"Implement a stack for which you can get the min element in O(1) time and O(1) space.\n";
Console.WriteLine(intro);
var stack = new MinEleIntStack();
string input = "default";
while (input != "done")
{
Console.WriteLine("\nEnter Stack command or \"done\"");
input = Console.ReadLine();
string[] commands = input.Split(' ');
if (commands[0] == "push")
{
var item = commands[1];
stack.Push(int.Parse(item));
Console.WriteLine($"\nPushed: {item}\n");
Console.WriteLine($"Also, the min is: {stack.GetMinEle()}");
}
else if (commands[0] == "pop")
{
Console.WriteLine($"\nPopped: {stack.Pop()}\n");
Console.WriteLine($"Also, the min is: {stack.GetMinEle()}");
}
}
}
public class MinEleIntStack
{
private readonly Stack<int> stack;
// minEle has no meaning if the stack is empty
private int minEle;
public MinEleIntStack()
{
stack = new Stack<int>();
}
public int Pop()
{
if (stack.Count == 0)
throw new InvalidOperationException("Stack is empty.");
var topOfStackVal = stack.Pop();
if (topOfStackVal >= minEle)
return topOfStackVal;
else
{
// The thing being popped actually represents the minEle on the stack
var minEleActuallyOnTopOfStack = minEle;
minEle = minEleActuallyOnTopOfStack + minEleActuallyOnTopOfStack - topOfStackVal;
return minEleActuallyOnTopOfStack;
}
}
public void Push(int actualItem)
{
if (stack.Count == 0)
{
stack.Push(actualItem);
minEle = actualItem;
}
else if (actualItem >= minEle)
stack.Push(actualItem);
else
{
// Don't push actualItem, since it is the new minEle.
// Insetad push "2x - minEle"
stack.Push(actualItem+actualItem-minEle);
minEle = actualItem;
}
}
public int GetMinEle()
{
if (stack.Count == 0)
throw new InvalidOperationException("Stack is empty.");
return minEle;
}
}
}
}