88"""
99
1010
11- def calculation_span (price , s ):
11+ def calculate_span (price : list [int ]) -> list [int ]:
12+ """
13+ Calculate the span values for a given list of stock prices.
14+ Args:
15+ price: List of stock prices.
16+ Returns:
17+ List of span values.
18+
19+ >>> calculate_span([10, 4, 5, 90, 120, 80])
20+ [1, 1, 2, 4, 5, 1]
21+ >>> calculate_span([100, 50, 60, 70, 80, 90])
22+ [1, 1, 2, 3, 4, 5]
23+ >>> calculate_span([5, 4, 3, 2, 1])
24+ [1, 1, 1, 1, 1]
25+ >>> calculate_span([1, 2, 3, 4, 5])
26+ [1, 2, 3, 4, 5]
27+ >>> calculate_span([10, 20, 30, 40, 50])
28+ [1, 2, 3, 4, 5]
29+ >>> calculate_span([100, 80, 60, 70, 60, 75, 85])
30+ [1, 1, 1, 2, 1, 4, 6]
31+ """
1232 n = len (price )
33+ s = [0 ] * n
1334 # Create a stack and push index of fist element to it
1435 st = []
1536 st .append (0 )
@@ -21,18 +42,20 @@ def calculation_span(price, s):
2142 for i in range (1 , n ):
2243 # Pop elements from stack while stack is not
2344 # empty and top of stack is smaller than price[i]
24- while len (st ) > 0 and price [st [0 ]] <= price [i ]:
45+ while len (st ) > 0 and price [st [- 1 ]] <= price [i ]:
2546 st .pop ()
2647
2748 # If stack becomes empty, then price[i] is greater
2849 # than all elements on left of it, i.e. price[0],
2950 # price[1], ..price[i-1]. Else the price[i] is
3051 # greater than elements after top of stack
31- s [i ] = i + 1 if len (st ) <= 0 else (i - st [0 ])
52+ s [i ] = i + 1 if len (st ) <= 0 else (i - st [- 1 ])
3253
3354 # Push this element to stack
3455 st .append (i )
3556
57+ return s
58+
3659
3760# A utility function to print elements of array
3861def print_array (arr , n ):
@@ -42,10 +65,9 @@ def print_array(arr, n):
4265
4366# Driver program to test above function
4467price = [10 , 4 , 5 , 90 , 120 , 80 ]
45- S = [0 for i in range (len (price ) + 1 )]
4668
47- # Fill the span values in array S[]
48- calculation_span (price , S )
69+ # Calculate the span values
70+ S = calculate_span (price )
4971
5072# Print the calculated span values
5173print_array (S , len (price ))
0 commit comments