1
+ '''
2
+ The stock span problem is a financial problem where we have a series of n daily
3
+ price quotes for a stock and we need to calculate span of stock’s price for all n days.
4
+
5
+ The span Si of the stock’s price on a given day i is defined as the maximum
6
+ number of consecutive days just before the given day, for which the price of the stock
7
+ on the current day is less than or equal to its price on the given day.
8
+ '''
9
+ def calculateSpan (price , S ):
10
+
11
+ n = len (price )
12
+ # Create a stack and push index of fist element to it
13
+ st = []
14
+ st .append (0 )
15
+
16
+ # Span value of first element is always 1
17
+ S [0 ] = 1
18
+
19
+ # Calculate span values for rest of the elements
20
+ for i in range (1 , n ):
21
+
22
+ # Pop elements from stack whlie stack is not
23
+ # empty and top of stack is smaller than price[i]
24
+ while ( len (st ) > 0 and price [st [0 ]] <= price [i ]):
25
+ st .pop ()
26
+
27
+ # If stack becomes empty, then price[i] is greater
28
+ # than all elements on left of it, i.e. price[0],
29
+ # price[1], ..price[i-1]. Else the price[i] is
30
+ # greater than elements after top of stack
31
+ S [i ] = i + 1 if len (st ) <= 0 else (i - st [0 ])
32
+
33
+ # Push this element to stack
34
+ st .append (i )
35
+
36
+
37
+ # A utility function to print elements of array
38
+ def printArray (arr , n ):
39
+ for i in range (0 ,n ):
40
+ print arr [i ],
41
+
42
+
43
+ # Driver program to test above function
44
+ price = [10 , 4 , 5 , 90 , 120 , 80 ]
45
+ S = [0 for i in range (len (price )+ 1 )]
46
+
47
+ # Fill the span values in array S[]
48
+ calculateSpan (price , S )
49
+
50
+ # Print the calculated span values
51
+ printArray (S , len (price ))
0 commit comments