Created
April 24, 2022 09:30
-
-
Save SuvidhaMalaviya/d3e9a3fbf6369527a3c9f11b63b8c941 to your computer and use it in GitHub Desktop.
You have an empty sequence, and you will be given queries. Each query is one of these three types: 1 x -Push the element x into the stack.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
import java.util.stream.*; | |
import static java.util.stream.Collectors.joining; | |
import static java.util.stream.Collectors.toList; | |
class Result { | |
/* | |
* Complete the 'getMax' function below. | |
* | |
* The function is expected to return an INTEGER_ARRAY. | |
* The function accepts STRING_ARRAY operations as parameter. | |
*/ | |
public static List<Integer> getMax(List<String> operations) { | |
List<Integer> stack = new ArrayList<>(); | |
List<Integer> output = new ArrayList<>(); | |
int max = Integer.MIN_VALUE; | |
for (int i = 0; i < operations.size(); i++) { | |
List<Integer> op = Arrays.stream(operations.get(i).split(" ")) | |
.map(Integer::valueOf) | |
.collect(Collectors.toList()); | |
int opCode = op.get(0); | |
switch (opCode){ | |
case 1: | |
stack.add(op.get(1)); | |
if(op.get(1)>max) | |
max = op.get(1); | |
break; | |
case 2: | |
int removedElement = stack.get(stack.size()-1); | |
stack.remove(stack.size()-1); | |
if(max==removedElement){ | |
max = Integer.MIN_VALUE; | |
for(int j=0;j<stack.size();j++){ | |
if(stack.get(j)>max) | |
max = stack.get(j); | |
} | |
} | |
break; | |
case 3: | |
output.add(max); | |
break; | |
} | |
} | |
return output; | |
} | |
} | |
public class MaximumElement { | |
public static void main(String[] args) throws IOException { | |
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); | |
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); | |
int n = Integer.parseInt(bufferedReader.readLine().trim()); | |
List<String> ops = IntStream.range(0, n).mapToObj(i -> { | |
try { | |
return bufferedReader.readLine(); | |
} catch (IOException ex) { | |
throw new RuntimeException(ex); | |
} | |
}) | |
.collect(toList()); | |
List<Integer> res = Result.getMax(ops); | |
bufferedWriter.write( | |
res.stream() | |
.map(Object::toString) | |
.collect(joining("\n")) | |
+ "\n" | |
); | |
bufferedReader.close(); | |
bufferedWriter.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment