forked from Srinivas11789/AlgorithmNuggets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp.py
More file actions
39 lines (35 loc) · 1.17 KB
/
temp.py
File metadata and controls
39 lines (35 loc) · 1.17 KB
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
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
"""
# Brute force solution - time limit exceeded - 2 for loop
n = len(temperatures)
result = []
for i in range(n):
for j in range(i+1,n):
if temperatures[j] > temperatures[i]:
result.append(j-i)
break
if j == n-1:
result.append(0)
break
if i == n-1:
result.append(0)
return result
"""
# Optimized Approach
# Result array
result = [0]*len(temperatures)
# Reference stack to track
stack = []
# Enumerate so we have index, value
for index, value in enumerate(temperatures):
# Iterate the stack when higher temperature is hit
while stack and temperatures[stack[-1]] < value:
select = stack.pop()
result[select] = index - select
stack.append(index)
return result