The Stock Span Problem | An efficient method to calculate stock span values implementing the same idea without using stack ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; A utility function to print elements of array ; Driver code ; Fill the span values in array S [ ] ; Print the calculated span values
def calculateSpan ( A , n , ans ) : NEW_LINE INDENT ans [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT counter = 1 NEW_LINE while ( ( i - counter ) >= 0 and A [ i ] >= A [ i - counter ] ) : NEW_LINE INDENT counter += ans [ i - counter ] NEW_LINE DEDENT ans [ i ] = counter NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT price = [ 10 , 4 , 5 , 90 , 120 , 80 ] NEW_LINE n = len ( price ) NEW_LINE S = [ 0 ] * ( n ) NEW_LINE calculateSpan ( price , n , S ) NEW_LINE printArray ( S , n ) NEW_LINE