I have solved the following problem. My code works but Hackerrank says that I can do faster:
There are plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.
Input Format
The input consists of an integer . The next line consists of integers describing the array where denotes the amount of pesticide in plant .
Constraints
\$1 \leq N \leq 100000\$
\$0 \leq P[i] \leq 10^9\$
Output Format
Output a single value equal to the number of days after which no plants die.
Sample Input
7 6 5 8 4 7 10 9
Sample Output
2
My code:
import java.io.*;
import java.util.*;
public class Solution {
static Stack<Integer> aStack = new Stack<Integer>();
static Stack<Integer> bStack = new Stack<Integer>();
static int printDays(Stack aStack){
int objectsRemoved=-1;
int countLoops=0;
while(objectsRemoved!=0) {
objectsRemoved=0;
int prevValue=0;
int curValue=0;
while(!aStack.isEmpty()) {
curValue = (int)aStack.pop();
if(!aStack.isEmpty()){
int tempValue = (int)aStack.pop();
if(curValue<=tempValue){
bStack.push(curValue);
}
else{
objectsRemoved++;
//System.out.println("Removed " + curValue);
}
aStack.push(tempValue);
}
else{
bStack.push(curValue);
}
}
while(!bStack.isEmpty()) {
aStack.push(bStack.pop());
}
if(objectsRemoved!=0){
countLoops++;
}
}
return countLoops;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
aStack.push(in.nextInt());
}
System.out.println(printDays(aStack));
}
}
Any recommendations to make it faster?