📜  跟踪堆栈中的当前最大元素

📅  最后修改于: 2022-05-13 01:57:09.139000             🧑  作者: Mango

跟踪堆栈中的当前最大元素

给定一个堆栈,跟踪其中的最大值。最大值可能是堆栈的顶部元素,但是一旦新元素被压入或从堆栈中弹出一个元素,现在最大元素将来自其余元素。
例子:

Input : 4 19 7 14 20
Output : Max Values in stack are 
         4 19 19 19 20

Input : 40 19 7 14 20 5
Output :  Max Values in stack are 
         40 40 40 40 40 40

方法1(蛮力) :我们不断推入主堆栈中的元素,每当我们被要求返回最大元素时,我们遍历堆栈并打印最大元素。
时间复杂度:O(n)
辅助空间:O(1)
方法 2(高效) :一种有效的方法是在将元素压入主堆栈时保持辅助堆栈。该辅助堆栈将跟踪最大元素。
以下是执行此操作的分步算法

  1. 创建一个辅助堆栈,例如“trackStack”以跟踪最大元素
  2. 将第一个元素推送到 mainStack 和 trackStack。
  3. 现在从第二个元素,将元素推送到主堆栈。将该元素与track Stack的顶部元素进行比较,如果当前元素大于trackStack的顶部,则将当前元素推入trackStack,否则将trackStack的顶部元素再次推入其中。
  4. 如果我们从主栈中弹出一个元素,那么也从 trackStack 中弹出一个元素。
  5. 现在要计算任意点主堆栈的最大值,我们可以简单地打印 Track stack 的顶部元素。

一步一步的解释:
假设元素以 {4, 2, 14, 1, 18} 的顺序被压入堆栈
第 1 步:按 4,电流最大值:4
第 2 步:按 2,电流最大值:4
第 3 步:按 14,电流最大值:14
第 4 步:按 1,电流最大值:14
第 5 步:按 18,电流最大值:18
第 6 步: Pop 18,当前最大值:14

下面是上述方法的实现:

C++
// C++ program to keep track of maximum
// element in a stack
#include 
using namespace std;
 
class StackWithMax
{
    // main stack
    stack mainStack;
 
    // stack to keep track of max element
    stack trackStack;
 
public:
    void push(int x)
    {
        mainStack.push(x);
        if (mainStack.size() == 1)
        {
            trackStack.push(x);
            return;
        }
 
        // If current element is greater than
        // the top element of track stack, push
        // the current element to track stack
        // otherwise push the element at top of
        // track stack again into it.
        if (x > trackStack.top())
            trackStack.push(x);
        else
            trackStack.push(trackStack.top());
    }
 
    int getMax()
    {
        return trackStack.top();
    }
 
    int pop()
    {
        mainStack.pop();
        trackStack.pop();
    }
};
 
// Driver program to test above functions
int main()
{
    StackWithMax s;
    s.push(20);
    cout << s.getMax() << endl;
    s.push(10);
    cout << s.getMax() << endl;
    s.push(50);
    cout << s.getMax() << endl;
    return 0;
}


Java
// Java program to keep track of maximum
// element in a stack
import java.util.*;
class GfG {
 
static class StackWithMax
{
    // main stack
    static Stack mainStack = new Stack ();
 
    // Stack to keep track of max element
    static Stack trackStack = new Stack ();
 
static void push(int x)
    {
        mainStack.push(x);
        if (mainStack.size() == 1)
        {
            trackStack.push(x);
            return;
        }
 
        // If current element is greater than
        // the top element of track stack, push
        // the current element to track stack
        // otherwise push the element at top of
        // track stack again into it.
        if (x > trackStack.peek())
            trackStack.push(x);
        else
            trackStack.push(trackStack.peek());
    }
 
    static int getMax()
    {
        return trackStack.peek();
    }
 
    static void pop()
    {
        mainStack.pop();
        trackStack.pop();
    }
};
 
// Driver program to test above functions
public static void main(String[] args)
{
    StackWithMax s = new StackWithMax();
    s.push(20);
    System.out.println(s.getMax());
    s.push(10);
    System.out.println(s.getMax());
    s.push(50);
    System.out.println(s.getMax());
}
}


Python3
# Python3 program to keep track of
# maximum element in a stack
 
class StackWithMax:
    def __init__(self):
         
        # main stack
        self.mainStack = []
     
        # stack to keep track of
        # max element
        self.trackStack = []
 
    def push(self, x):
        self.mainStack.append(x)
        if (len(self.mainStack) == 1):
            self.trackStack.append(x)
            return
 
        # If current element is greater than
        # the top element of track stack,
        # append the current element to track
        # stack otherwise append the element
        # at top of track stack again into it.
        if (x > self.trackStack[-1]):
            self.trackStack.append(x)
        else:
            self.trackStack.append(self.trackStack[-1])
 
    def getMax(self):
        return self.trackStack[-1]
 
    def pop(self):
        self.mainStack.pop()
        self.trackStack.pop()
 
# Driver Code
if __name__ == '__main__':
 
    s = StackWithMax()
    s.push(20)
    print(s.getMax())
    s.push(10)
    print(s.getMax())
    s.push(50)
    print(s.getMax())
 
# This code is contributed by PranchalK


C#
// C# program to keep track of maximum
// element in a stack
using System;
using System.Collections.Generic;
 
class GfG
{
 
public class StackWithMax
{
    // main stack
    static Stack mainStack = new Stack ();
 
    // stack to keep track of max element
    static Stack trackStack = new Stack ();
 
    public void push(int x)
    {
        mainStack.Push(x);
        if (mainStack.Count == 1)
        {
            trackStack.Push(x);
            return;
        }
 
        // If current element is greater than
        // the top element of track stack, push
        // the current element to track stack
        // otherwise push the element at top of
        // track stack again into it.
        if (x > trackStack.Peek())
            trackStack.Push(x);
        else
            trackStack.Push(trackStack.Peek());
    }
 
    public int getMax()
    {
        return trackStack.Peek();
    }
 
    public void pop()
    {
        mainStack.Pop();
        trackStack.Pop();
    }
};
 
// Driver code
public static void Main()
{
    StackWithMax s = new StackWithMax();
    s.push(20);
    Console.WriteLine(s.getMax());
    s.push(10);
    Console.WriteLine(s.getMax());
    s.push(50);
    Console.WriteLine(s.getMax());
}
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


输出:

20
20
50