Daily Temperatures
Problem
For each day print how many days you must wait for a warmer temperature. If there is no warmer day, print 0.
Constraints
- 1 <= n <= 10^5
Examples
Input
8 73 74 75 71 69 72 76 73
Output
1 1 4 2 1 1 0 0
Solutions
This is the next greater element problem, but we store the distance between the indexes. The stack idea is the same.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The waiting days.
* Approach: A monotonic stack.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
int[] result = new int[a.length];
// Step 1: The stack keeps the indexes of days that still wait for a warmer day.
java.util.ArrayDeque<Integer> stack = new java.util.ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
// Step 2: Today is warmer than the waiting days on top. Their waiting time is the difference of the indexes.
while (!stack.isEmpty() && a[stack.peek()] < a[i]) {
int day = stack.pop();
result[day] = i - day;
}
// Step 3: Today waits for a warmer day.
stack.push(i);
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- What do we store in the answer: the value or the distance?