Skip to content

Commit b5b6cd6

Browse files
committed
stock span
1 parent b0b85fe commit b5b6cd6

2 files changed

Lines changed: 81 additions & 2 deletions

File tree

‎stack/NearestGreaterToLeft.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def NGLStack(arr):
4242
if s.top() > arr[i]:
4343
ans.append(s.top())
4444
else:
45-
while not s.isEmpty() and s.top() <= arr[i]:
45+
while not s.isEmpty() and s.top <= arr[i]:
4646
s.pop()
4747
if s.isEmpty():
4848
ans.append(-1)
@@ -55,7 +55,7 @@ def NGLStack(arr):
5555

5656
def main():
5757
arr = [1, 3, 2, 4]
58-
NGLSimple(arr)
58+
NGLS?!?jedi=0, imple(arr)?!? (*_**values: object*_*, sep: Optional[Text]=..., end: Optional[Text]=..., file: Optional[_Writer]=..., flush: bool=...) ?!?jedi?!?
5959
print(NGLStack(arr))
6060

6161

‎stack/stockSpanProblem.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# simple
2+
3+
4+
def stockSpanProblem(arr):
5+
length = len(arr)
6+
ans = [None] * length
7+
ans[0] = 1
8+
for i in range(1, length):
9+
ans[i] = 1
10+
11+
j = i - 1
12+
while j >= 0 and arr[i] >= arr[j]:
13+
ans[i] += 1
14+
j -= 1
15+
16+
print(ans)
17+
18+
19+
class Stack:
20+
"""
21+
class for creating stack DS
22+
function it have :
23+
push -> push value to stack
24+
pop -> return a value out of stack
25+
isEmpty -> return true if stack is empty
26+
top -> return value from stack without removing it
27+
"""
28+
29+
def __init__(self):
30+
self.stack = []
31+
32+
def push(self, index, element):
33+
self.stack.append([index, element])
34+
35+
def isEmpty(self):
36+
return True if len(self.stack) == 0 else False
37+
38+
def pop(self):
39+
return -1 if self.isEmpty() else self.stack.pop()
40+
41+
def top(self):
42+
return self.stack[-1] if not self.isEmpty() else -1
43+
44+
45+
def stockSpanProblemStack(arr):
46+
length = len(arr)
47+
s = Stack()
48+
49+
ans = []
50+
51+
for i in range(0, length):
52+
if s.isEmpty():
53+
ans.append(-1)
54+
else:
55+
if s.top()[1] > arr[i]:
56+
ans.append(s.top()[0])
57+
else:
58+
while not s.isEmpty() and s.top()[1] <= arr[i]:
59+
s.pop()
60+
if s.isEmpty():
61+
ans.append(-1)
62+
else:
63+
ans.append(s.top()[0])
64+
s.push(i, arr[i])
65+
66+
for i in range(length):
67+
ans[i] = i - ans[i]
68+
69+
return ans
70+
71+
72+
def main():
73+
arr = [10, 4, 5, 90, 120, 80]
74+
stockSpanProblem(arr)
75+
print(stockSpanProblemStack(arr))
76+
77+
78+
if __name__ == "__main__":
79+
main()

0 commit comments

Comments
 (0)