the stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock s price for all n days the span si of the stock s price on a given day i is defined as the maximum number of consecutive days just before the given day for which the price of the stock on the current day is less than or equal to its price on the given day create a stack and push index of fist element to it span value of first element is always 1 calculate span values for rest of the elements pop elements from stack while stack is not empty and top of stack is smaller than pricei if stack becomes empty then pricei is greater than all elements on left of it i e price0 price1 pricei1 else the pricei is greater than elements after top of stack push this element to stack a utility function to print elements of array driver program to test above function fill the span values in array s print the calculated span values create a stack and push index of fist element to it span value of first element is always 1 calculate span values for rest of the elements pop elements from stack while stack is not empty and top of stack is smaller than price i if stack becomes empty then price i is greater than all elements on left of it i e price 0 price 1 price i 1 else the price i is greater than elements after top of stack push this element to stack a utility function to print elements of array driver program to test above function fill the span values in array s print the calculated span values
def calculation_span(price, s):
    n = len(price)
    
    st = []
    st.append(0)

    
    s[0] = 1

    
    for i in range(1, n):
        
        
        while len(st) > 0 and price[st[0]] <= price[i]:
            st.pop()

        
        
        
        
        s[i] = i + 1 if len(st) <= 0 else (i - st[0])

        
        st.append(i)



def print_array(arr, n):
    for i in range(n):
        print(arr[i], end=" ")



price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price) + 1)]


calculation_span(price, S)


print_array(S, len(price))