Courtesy of a few posts around here I've discovered HackerRank. Poisonous Plants is one of their challenges.
Of course, skip the following if you'd like to try it yourself.
Challenge:
There are \$N\$ 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, it dies.
Given the initial values of 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 \$N\$. The next line consists of N integers describing the array
P
whereP[i]
denotes the amount of pesticide in planti
.
Constraints:
- \$1 \le N \le 100000\$
- \$0 \le P[i] \le 10^9\$
Output Format:
Output a single value equal to the number of days after which no plants die.
Solution:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] garden = new int[input.nextInt()];
for (int i = 0; i < garden.length; i++) {
garden[i] = input.nextInt();
}
int days = 0;
while(killCommand(garden)) {
days++;
}
System.out.println(days);
}
private static boolean killCommand(int[] garden) {
boolean plantDied = false;
int lastIndex = garden.length - 1;
int last = garden[lastIndex];
for (int i = lastIndex - 1; i >= 0; i--) {
if (garden[i] == -1) {
continue;
}
int current = garden[i];
if (current < last) {
plantDied = true;
garden[lastIndex] = -1;
}
last = current;
lastIndex = i;
}
return plantDied;
}
}
Sample Input:
7
6 5 8 4 7 10 9
Sample Output:
2
My algorithm works and passes 21 of 23 test cases, but doesn't meet their allotted time for two. How can it be further optimized?