svephoto

Poisonous Plants [Java]

Aug 25th, 2021 (edited)
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.ArrayDeque;
  5.  
  6. public class PoisonousPlants {
  7.     public static void main(String[] args) throws IOException {
  8.         BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  9.  
  10.         int n = Integer.parseInt(input.readLine());
  11.  
  12.         String[] plants = input.readLine().split(" ");
  13.  
  14.         ArrayDeque<Integer> indexes = new ArrayDeque<>();
  15.         indexes.push(0);
  16.  
  17.         int[] daysCount = new int[n];
  18.  
  19.         for (int a = 0; a < n; a++) {
  20.             int maxDays = 0;
  21.  
  22.             while (indexes.size() > 0 && Integer.parseInt(plants[indexes.peek()]) >= Integer.parseInt(plants[a])) {
  23.                 maxDays = Math.max(maxDays, daysCount[indexes.pop()]);
  24.             }
  25.  
  26.             if (indexes.size() > 0) {
  27.                 daysCount[a] = maxDays + 1;
  28.             }
  29.  
  30.             indexes.push(a);
  31.         }
  32.  
  33.         System.out.println(maxCalc(daysCount));
  34.     }
  35.  
  36.     private static int maxCalc(int[] days) {
  37.         int max = Integer.MIN_VALUE;
  38.  
  39.         for (int currentDay : days) {
  40.             if (currentDay > max) {
  41.                 max = currentDay;
  42.             }
  43.         }
  44.  
  45.         return max;
  46.     }
  47. }
  48.  
Add Comment
Please, Sign In to add comment