Max Stack (with getMax)

beginner
8 min

Max Stack (with getMax)

Welcome to a comprehensive guide on building a Max Stack with a getMax function! In this lesson, we'll delve into the world of data structures, focusing on stacks, and learn how to implement a custom stack with an additional getMax feature. This tutorial is designed for both beginners and intermediate learners, so let's get started!

Understanding Stacks šŸ“

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It's like a pile of plates where you can only add or remove plates from the top. In programming, stacks are fundamental and widely used in many real-world applications.

Introducing Max Stack šŸŽÆ

Max Stack is a custom data structure that combines the functionality of a regular stack and a maximum finder. It maintains a separate maximum value in addition to the elements, allowing you to find the maximum element at any given time.

Implementing Max Stack with getMax Function šŸ’”

Here's a simple implementation of Max Stack in Python:

python
class MaxStack: def __init__(self): self.stack = [] self.max_stack = [] def push(self, value): self.stack.append(value) if not self.max_stack or self.max_stack[-1] < value: self.max_stack.append(value) else: self.max_stack.append(self.max_stack[-1]) def pop(self): if not self.stack: return "Stack is empty" popped_value = self.stack.pop() if popped_value == self.max_stack[-1]: self.max_stack.pop() return popped_value def getMax(self): if not self.max_stack: return "Stack is empty" return self.max_stack[-1]

Pushing Elements šŸŽÆ

In the push function, we're adding elements to both the stack and the maximum stack. If the new element is greater than the current maximum, we update the maximum stack's top element. Otherwise, we simply append the current maximum to the maximum stack.

Popping Elements šŸŽÆ

The pop function removes the top element from the stack and updates the maximum stack if the popped element was the maximum.

Finding the Maximum šŸŽÆ

The getMax function returns the maximum element currently in the maximum stack.

Practical Application šŸ“

Max Stack is useful in real-world scenarios where you need to maintain a running maximum or find the maximum element at any given time without iterating through the entire list, such as:

  • Stock price tracking
  • Finding the maximum subarray sum in an array
  • Solving mathematical expressions with parentheses

Quiz Time! šŸŽÆ

Quick Quiz
Question 1 of 1

What principle does a stack follow?

Quick Quiz
Question 1 of 1

What does the `getMax` function return in an empty MaxStack?