def daily_temperatures(temps):
stack=[]; res=[0]*len(temps)
for i,t in enumerate(temps):
while stack and temps[stack[-1]]<t:
idx=stack.pop(); res[idx]=i-idx
stack.append(i)
return res
public int[] dailyTemperatures(int[] temps){
Stack<Integer> stack=new Stack<>();
int[] res=new int[temps.length];
for(int i=0;i<temps.length;i++){
while(!stack.isEmpty()&&temps[stack.peek()]<temps[i]){
int idx=stack.pop(); res[idx]=i-idx;
} stack.push(i);
} return res;
}
Monotonic stack. 'while stack' vs !isEmpty(). enumerate vs index.
def daily_temperatures(temps):
stack=[]; res=[0]*len(temps)
for i,t in enumerate(temps):
while stack and temps[stack[-1]]<t:
idx=stack.pop(); res[idx]=i-idx
stack.append(i)
return res
public int[] dailyTemperatures(int[] temps){
Stack<Integer> stack=new Stack<>();
int[] res=new int[temps.length];
for(int i=0;i<temps.length;i++){
while(!stack.isEmpty()&&temps[stack.peek()]<temps[i]){
int idx=stack.pop(); res[idx]=i-idx;
} stack.push(i);
} return res;
}
1. Monotonic decreasing stack 2. Pop when warmer found 3. Record gap