This repository has been archived by the owner on Oct 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Temperature_prob
55 lines (48 loc) · 1.93 KB
/
Temperature_prob
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
import java.util.Stack;
public class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] answer = new int[n]; // Result array initialized to all 0s
Stack<Integer> stack = new Stack<>(); // Stack to store indices
for (int i = 0; i < n; i++) {
// While stack is not empty and the current temperature is warmer
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int prevIndex = stack.pop(); // Get the index of the colder day
answer[prevIndex] = i - prevIndex; // Calculate the number of days to wait
}
// Push the current day index onto the stack
stack.push(i);
}
return answer;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Example 1
int[] temperatures1 = {73, 74, 75, 71, 69, 72, 76, 73};
int[] result1 = sol.dailyTemperatures(temperatures1);
System.out.println("Temperatures: [73, 74, 75, 71, 69, 72, 76, 73]");
System.out.print("Days to wait: ");
for (int r : result1) {
System.out.print(r + " ");
}
System.out.println("\n");
// Example 2
int[] temperatures2 = {30, 40, 50, 60};
int[] result2 = sol.dailyTemperatures(temperatures2);
System.out.println("Temperatures: [30, 40, 50, 60]");
System.out.print("Days to wait: ");
for (int r : result2) {
System.out.print(r + " ");
}
System.out.println("\n");
// Example 3
int[] temperatures3 = {30, 60, 90};
int[] result3 = sol.dailyTemperatures(temperatures3);
System.out.println("Temperatures: [30, 60, 90]");
System.out.print("Days to wait: ");
for (int r : result3) {
System.out.print(r + " ");
}
System.out.println();
}
}