-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPoisonousPlants.java
73 lines (51 loc) · 2.02 KB
/
PoisonousPlants.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.Stack;
public class Solution {
private static class Plant {
int pesticide;
int daysAlive;
public Plant (int pesticide, int daysAlive) {
this.pesticide = pesticide;
this.daysAlive = daysAlive;
}
}
static int poisonousPlants(int[] p) {
Stack<Plant> stack = new Stack<>();
int maxDays = 0;
for (Integer n: p) {
int days = 0;
while (!stack.isEmpty() && n <= stack.peek().pesticide) { // We search for previous plant that can't kill us
days = Math.max(days, stack.pop().daysAlive); // That plant days indicates how long we'll survive (Delete previous - it won't kill us)
}
if (stack.isEmpty()) { //As stack is empty, we know current plant won't be killed
days = 0;
} else { // Current plant will survive one day longer than previous max
days++;
}
maxDays = Math.max(maxDays, days);
stack.push(new Plant(n, days)); // We take previous plant maxDays
}
return maxDays;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] p = new int[n];
String[] pItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int pItem = Integer.parseInt(pItems[i]);
p[i] = pItem;
}
int result = poisonousPlants(p);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}