NeetCode #366LC-716HardStackNC Algo100
← Back to All Problems#366 · #716 · Max Stack(最大栈)
📌 Problem Statement & Constraints
Design a max stack supporting
push(x), pop(), top(), peekMax() and popMax(). popMax() removes and returns the maximum element; if there are several, remove the one closest to the top. Constraints: -10^7 <= x <= 10^7; at most 10^4 calls.💡 Core Algorithmic Approaches
- A plain list supports
push,popandtopin O(1), andpeekMaxin O(n). popMaxneeds to remove the topmost occurrence of the maximum, which is the last occurrence in list order.- Finding that index is
len(st) - 1 - st[::-1].index(m). - A fully optimal design uses a doubly linked list plus a sorted structure for O(log n) operations; the list version is far simpler and fast enough at these limits.
💻 Benchmark Python3 Implementation
class MaxStack:
def __init__(self):
self.st = []
def push(self, x: int) -> None:
self.st.append(x)
def pop(self) -> int:
return self.st.pop()
def top(self) -> int:
return self.st[-1]
def peekMax(self) -> int:
return max(self.st)
def popMax(self) -> int:
m = max(self.st)
# the topmost occurrence of the maximum is the LAST one in list order
i = len(self.st) - 1 - self.st[::-1].index(m)
return self.st.pop(i)
# Balanced-tree variant for O(log n) operations
class MaxStack2:
def __init__(self):
self.st = []
self.id = 0
self.heap = [] # (-value, -id) for max-first, top-first
self.removed = set()
def push(self, x: int) -> None:
import heapq
self.st.append((x, self.id))
heapq.heappush(self.heap, (-x, -self.id))
self.id += 1
def _clean(self) -> None:
import heapq
while self.heap and self.heap[0][1] in self.removed:
heapq.heappop(self.heap)
def pop(self) -> int:
v, i = self.st.pop()
self.removed.add(-i)
return v
def top(self) -> int:
return self.st[-1][0]
def peekMax(self) -> int:
self._clean()
return -self.heap[0][0]
def popMax(self) -> int:
self._clean()
negv, negi = self.heap[0]
i = -negi
self.removed.add(i)
# remove the specific entry from the stack
for k in range(len(self.st) - 1, -1, -1):
if self.st[k][1] == i:
self.st.pop(k)
break
return -negv⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1) for push/pop/top and O(n) for peekMax/popMax in the list version. The heap variant achieves O(log n) amortised for all operations.
💾 Space Complexity
O(n).
⚠️ Interview Pitfalls & Follow-ups
- Removing the first occurrence of the maximum in
popMax: the requirement is the topmost one, i.e. the last occurrence in list order. - Using
st.index(m): that finds the first occurrence, which is the wrong one. - Assuming
peekMaxmust be O(1): the problem does not require it; only a full doubly-linked-list design would achieve that. - Forgetting the lazy-deletion set in the heap variant: stale heap entries would return removed values.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
最大栈
设计一个最大栈数据结构,既支持栈操作,又支持查找栈中最大元素。实现 MaxStack 类: push(x) 将元素 x 压入栈中; pop() 移除栈顶元素并返回; top() 返回栈顶元素; peekMax() 检索栈中的最大元素; popMax() 移除栈中的最大元素并返回它;如果有多个最大元素,只移除 最靠近顶部 的那个。约束:-10^7 ≤ x ≤ 10^7;最多调用 10^4 次 push、pop、top、peekMax 和 popMax;题目保证每次调用时栈非空。
核心要点
- 主栈 + 辅助最大栈(标准解) : stack 存所有元素, max_stack 存「到当前位置为止的最大值」,两者同步压栈与弹栈。
- popMax 的实现(本题核心) :先取出当前最大值 mx = max_stack[-1] ;然后不断 pop() 并暂存到缓冲区,直到弹出值为 mx 为止;最后把缓冲区中的元素按原顺序重新 push 回去。
- 为什么用缓冲区而非直接删除 :栈无法从中间删除,只能把「最大值之上的所有元素」暂存,删除后再恢复。
- 复杂度 : popMax 最坏 O(n),其余操作 O(1)。
常见陷阱
- popMax 时忘记恢复暂存的元素 :会把最大值之上的元素全部丢弃。
- 恢复时未逆序 : buf 中保存的是「自上而下」的顺序,必须用 buf.pop() (即逆序)才能恢复原顺序。
- 多个最大值时删除的不是「最靠近顶部」的 :本解从栈顶往下找第一个等于 mx 的元素,恰好是「最靠近顶部」的那个。
- max_stack 不同步弹出 : pop 时必须同时弹两个栈。
- 用「排序 + 查找」实现 peekMax :O(n log n) 每次,效率低。辅助栈是 O(1)。
参考实现
class MaxStack:
def __init__(self):
self.stack = []
self.max_stack = [] # 到当前位置为止的最大值
def push(self, x: int) -> None:
self.stack.append(x)
self.max_stack.append(max(x, self.max_stack[-1]) if self.max_stack else x)
def pop(self) -> int:
self.max_stack.pop()
return self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def peekMax(self) -> int:
return self.max_stack[-1]
def popMax(self) -> int:
mx = self.max_stack[-1] # 当前最大值
buf = []
# 把最大值之上的元素全部暂存
while self.stack[-1] != mx:
buf.append(self.pop())
self.pop() # 弹出最大值本身
# 按原顺序恢复(buf 中是自上而下的顺序,故逆序 push)
while buf:
self.push(buf.pop())
return mx