How to find Min or Max value in a Stack with Go

Stack

type MinStack struct {
stack []int
min int
}
import "math"// ...func NewMinStack() MinStack {
min := math.MaxInt64
return MinStack{min: min}
}

Push

func (ms *MinStack) Push(item int) {
ms.stack = append(ms.stack, item)
if item < ms.min {
ms.min = item
}
}

Pop

func (ms *MinStack) Pop() {
length := len(ms.stack)
last := ms.stack[length-1]
ms.stack = ms.stack[:length-1]
if last != ms.min {
return
}
// ...
}
func (ms *MinStack) Pop() {
// ...
ms.min = math.MaxInt64
for _, x := range ms.stack {
if x < ms.min {
ms.min = x
}
}
}

GetTop

func (ms *MinStack) GetTop() int {
return ms.stack[len(ms.stack)-1]
}

GetMin

func (ms *MinStack) GetMin() int {
return ms.min
}

Full Solution

import "math"

type MinStack struct {
stack []int
min int
}
func NewMinStack() MinStack {
return MinStack{min: math.MaxInt64}
}
func (ms *MinStack) Push(item int) {
ms.stack = append(ms.stack, item)
if item < ms.min {
ms.min = item
}
}
func (ms *MinStack) Pop() {
length := len(ms.stack)
last := ms.stack[length-1]
ms.stack = ms.stack[:length-1]
if last != ms.min {
return
}
ms.min = math.MaxInt64
for _, x := range ms.stack {
if x < ms.min {
ms.min = x
}
}
}
func (ms *MinStack) GetTop() int {
return ms.stack[len(ms.stack)-1]
}
func (ms *MinStack) GetMin() int {
return ms.min
}

--

--

--

Software Engineer. Interested in Full-Stack Development and DevOps.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Leaning a new language!

Unix, Git & Github

Informatica MDM Training, 100% Free — The best Informatica Master data Management Tutorial

all_month_year_df = pd.pivot_table(df, values=”Open”,

GSoC17 : Client Side File Crypto : Week 12, Wrap-Up

2021 Roadmap To Become Java Developer

Deploying Spring Boot MVC on AWS Lambda using Serverless

Western Shooter Devblog #6 | Spawn System without the Clutter in Unity

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kirill Shevchenko

Kirill Shevchenko

Software Engineer. Interested in Full-Stack Development and DevOps.

More from Medium

Concurrency in Go Part -1

How Golang DB migration tool work?

Go: Introduction to Embed Package

Go WaitGroup doesn’t wait exec.Command finish