Didart

Poisonous Plants

Dec 29th, 2022
850
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. package StacksAndQueues1;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Scanner;
  5. import java.util.Stack;
  6.  
  7. public class PoisonousPlants {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.         int number = Integer.parseInt(scanner.nextLine());
  12.  
  13.         int[] plants = Arrays
  14.                 .stream(scanner.nextLine().split(" "))
  15.                 .mapToInt(Integer::parseInt)
  16.                 .toArray();
  17.         int[] days = new int[number];
  18.  
  19.         Stack<Integer> stack = new Stack<>();
  20.         stack.push(0);
  21.  
  22.         int max = -1;
  23.         for (int i = 1; i < plants.length; i++) {
  24.             int allDays = 0;
  25.             while (stack.size() > 0 && plants[stack.peek()] >= plants[i]) {
  26.                 allDays = Math.max(days[stack.pop()], allDays);
  27.             }
  28.             if (stack.size() > 0) {
  29.                 days[i] = allDays + 1;
  30.                 if (allDays + 1 > max) {
  31.                     max = allDays + 1;
  32.                 }
  33.             }
  34.             stack.push(i);
  35.         }
  36.         System.out.println(max);
  37.     }
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment