Skip to content

Commit 34366cf

Browse files
committed
add max stack problem
1 parent f57519c commit 34366cf

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ This is my way of saying - change your interview style. There are lots of smart
4242
| [count and say](https://leetcode.com/problems/count-and-say/) | [click](https://github.com/sagivo/algorithms/blob/master/src/count_and_say.rb) |
4343
| [Telephone number to words](http://www.mobilefish.com/services/phonenumber_words/phonenumber_words.php) | [click](https://github.com/sagivo/algorithms/blob/master/src/phone.rb) |
4444
| [Maximum contiguous subarray](https://leetcode.com/problems/maximum-subarray) | [click](https://github.com/sagivo/algorithms/blob/master/src/max_subarray.rb) |
45+
| [Max Stack](https://leetcode.com/problems/max-stack/submissions/) | [click](https://github.com/sagivo/algorithms/blob/master/src/max_stack.rb) |
4546
| [Find the smallest biggest number that has the same digits](http://stackoverflow.com/questions/9368205/given-a-number-find-the-next-higher-number-which-has-the-exact-same-set-of-digi) | [click](https://github.com/sagivo/algorithms/blob/master/src/bigger_num_with_same_digits.rb) |
4647
| [Find the minimum insertions needed to make a word palindrome](http://www.geeksforgeeks.org/dynamic-programming-set-28-minimum-insertions-to-form-a-palindrome/) | [click](https://github.com/sagivo/algorithms/blob/master/src/min_insertions_for_palindrome.rb) |
4748
| [String matching - Knuth Morris Pratt algorithm KMP](http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) | [click](https://github.com/sagivo/algorithms/blob/master/src/kmp.rb) |

src/max_stack.rb

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class MaxStack
2+
def initialize()
3+
@q = []
4+
@q2 = []
5+
end
6+
7+
def push(x)
8+
max = @q.any? ? [x, @q.last[1]].max : x
9+
@q << [x, max]
10+
x
11+
end
12+
13+
def pop()
14+
return nil unless @q.any?
15+
16+
ret = @q.pop[0]
17+
ret
18+
end
19+
20+
def top()
21+
return nil unless @q.any?
22+
@q.last[0]
23+
end
24+
25+
def peek_max()
26+
return nil unless @q.any?
27+
@q.last[1]
28+
end
29+
30+
31+
def pop_max()
32+
return nil unless @q.any?
33+
max = @q.last[1]
34+
q2 = []
35+
36+
while top() != max
37+
q2 << pop()
38+
end
39+
pop()
40+
41+
while q2.any?
42+
push(q2.pop)
43+
end
44+
max
45+
end
46+
end

0 commit comments

Comments
 (0)