borovaneca

test2

Feb 28th, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.87 KB | None | 0 0
  1. package Advance.StacksAndQueues.Exercise;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Arrays;
  5. import java.util.Scanner;
  6.  
  7. public class Test2 {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.  
  12.         int n = Integer.parseInt(scanner.nextLine());
  13.         ArrayDeque<Integer> plantsStack = getPlants(scanner.nextLine(), n);
  14.         ArrayDeque<Integer> container = new ArrayDeque<>();
  15.  
  16.         int dayCounter = 0;
  17.         while (true) {
  18.             int sizeBeforeCalc = plantsStack.size();
  19.  
  20.             while (!plantsStack.isEmpty()) {
  21.                 int currentPlant = plantsStack.pop();
  22.                 if (plantsStack.size() >= 1) {
  23.                     int plantOnLeft = plantsStack.peek();
  24.                     if (!(currentPlant > plantOnLeft)) {
  25.                         container.push(currentPlant);
  26.                 }
  27.  
  28.                 } else {
  29.                     container.push(currentPlant);
  30.                 }
  31.  
  32.             }
  33.  
  34.             moveBackRemainingPlants(plantsStack, container);
  35.             int sizeAfterCalc = plantsStack.size();
  36.  
  37.             if (sizeBeforeCalc == sizeAfterCalc) {
  38.                 break;
  39.             }
  40.             dayCounter++;
  41.         }
  42.  
  43.         System.out.println(dayCounter);
  44.  
  45.     }
  46.  
  47.     private static void moveBackRemainingPlants(ArrayDeque<Integer> plantsStack, ArrayDeque<Integer> container) {
  48.         while (!container.isEmpty()) {
  49.             plantsStack.push(container.pop());
  50.         }
  51.     }
  52.  
  53.     private static ArrayDeque<Integer> getPlants(String nextLine, int n) {
  54.         ArrayDeque<Integer> temporary = new ArrayDeque<>();
  55.         int[] pesticide = Arrays.stream(nextLine.split(" ")).mapToInt(Integer::parseInt).toArray();
  56.  
  57.         for (int i = 1; i <= n; i++) {
  58.             temporary.push(pesticide[i - 1]);
  59.         }
  60.         return temporary;
  61.     }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment