|
1 | 1 |
|
| 2 | +package AlgoExpert_Medium; |
| 3 | + |
| 4 | +import java.util.Map; |
| 5 | +import java.util.List; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.HashMap; |
| 8 | + |
| 9 | +public class MinMaxStackConstruction { |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + |
| 13 | + } |
| 14 | + |
| 15 | + static class MinMaxStack { |
| 16 | + |
| 17 | + List<Map<String, Integer>> minMaxStack = new ArrayList<Map<String, Integer>>() ; |
| 18 | + List<Integer> stack = new ArrayList<Integer>(); |
| 19 | + |
| 20 | + // O(1) time | O(1) space |
| 21 | + public int peek() { |
| 22 | + return stack.get(stack.size()-1); |
| 23 | + } |
| 24 | + |
| 25 | + // O(1) time | O(1) space |
| 26 | + public int pop() { |
| 27 | + minMaxStack.remove(minMaxStack.size()-1); |
| 28 | + return stack.remove(stack.size()-1); |
| 29 | + } |
| 30 | + |
| 31 | + // O(1) time | O(1) space |
| 32 | + public void push(Integer number) { |
| 33 | + Map<String, Integer> newMinMax = new HashMap<>(); |
| 34 | + newMinMax.put("min", number); |
| 35 | + newMinMax.put("max", number) ; |
| 36 | + |
| 37 | + if(!minMaxStack.isEmpty()) { |
| 38 | + Map<String, Integer> lastMinMax = |
| 39 | + new HashMap<>(minMaxStack.get(minMaxStack.size()-1)); |
| 40 | + newMinMax.replace("min", Math.min(lastMinMax.get("min"), number) ) ; |
| 41 | + newMinMax.replace("max", Math.max(lastMinMax.get("max"), number) ) ; |
| 42 | + } |
| 43 | + minMaxStack.add(newMinMax) ; |
| 44 | + stack.add(number); |
| 45 | + } |
| 46 | + |
| 47 | + // O(1) time | O(1) space |
| 48 | + public int getMin() { |
| 49 | + return minMaxStack.get(minMaxStack.size()-1).get("min"); |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + // O(1) time | O(1) space |
| 54 | + public int getMax() { |
| 55 | + return minMaxStack.get(minMaxStack.size()-1).get("max"); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | +} |
| 61 | +// All class methods should run in constant time and constant space. |
| 62 | + |
0 commit comments