So I am trying to solve https://leetcode.com/problems/daily-temperatures Basically given an array [30,40,50,60] we need to return the indices of the next increasing value so output would be [1,1,1,0] My algorithm is to
- while end !=0 read from the array
- if last element add 0 to output and stack
- Else if temperature[end] > stack top add to stack and add stack top to be the temperature difference.
- If temperature[end] <= stack top then we pop every element until this condition breaks and update the stack top and output.
I keep getting a time limit exceeded here, My understanding here is that the complexity is O(N). I am not sure how to optimise it further.
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
output = []
r = len(temperatures) - 1
stack = []
while r >= 0:
if r == len(temperatures) - 1:
stack.append(r)
output.insert(0, 0)
else:
if temperatures[stack[-1]] > temperatures[r]:
output.insert(0, stack[-1]-r)
stack.append(r)
else:
while stack and temperatures[stack[-1]] <= temperatures[r]:
stack.pop()
if len(stack) == 0:
output.insert(0, 0)
stack.append(r)
else:
output.insert(0, stack[-1]-r)
stack.append((r))
r -= 1
return output