borovaneca

test

Feb 28th, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. package Advance.StacksAndQueues.Exercise;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayDeque;
  7. import java.util.Deque;
  8.  
  9. public class Test {
  10.     public static void main(String[] args) throws IOException {
  11.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  12.         int n = Integer.parseInt(reader.readLine());
  13.         String[] tokens = reader.readLine().split(" ");
  14.         int[] plants = new int[n];
  15.         for (int i = 0; i < n; i++) {
  16.             plants[i] = Integer.parseInt(tokens[i]);
  17.         }
  18.         Deque<Integer> indices = new ArrayDeque<>();
  19.         indices.push(0);
  20.         int[] days = new int[n];
  21.         for (int i = 1; i < n; i++) {
  22.             int maxDays = 0;
  23.             while (!indices.isEmpty() && plants[indices.peek()] >= plants[i]) {
  24.                 maxDays = Math.max(maxDays, days[indices.pop()]);
  25.             }
  26.             if (!indices.isEmpty()) {
  27.                 days[i] = maxDays + 1;
  28.             }
  29.             indices.push(i);
  30.         }
  31.         System.out.println(getLastDay(days));
  32.     }
  33.  
  34.     private static int getLastDay(int[] days) {
  35.         int lastDay = 0;
  36.         for (int day : days) {
  37.             if (day > lastDay) {
  38.                 lastDay = day;
  39.             }
  40.         }
  41.         return lastDay;
  42.     }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment