The Stock Span Problem | method to calculate stock span values ; Span value of first day is always 1 ; Calculate span value of remaining days by linearly checking previous days ; Initialize span value ; Traverse left while the next element on left is smaller than price [ i ] ; A utility function to print elements of array ; Driver code ; Fill the span values in array S [ ] ; print the calculated span values
function calculateSpan ( price , n , S ) { S [ 0 ] = 1 ; for ( let i = 1 ; i < n ; i ++ ) { S [ i ] = 1 ; for ( let j = i - 1 ; ( j >= 0 ) && ( price [ i ] >= price [ j ] ) ; j -- ) S [ i ] ++ ; } } function printArray ( arr ) { let result = arr . join ( " " ) ; document . write ( result ) ; } let price = [ 10 , 4 , 5 , 90 , 120 , 80 ] ; let n = price . length ; let S = new Array ( n ) ; S . fill ( 0 ) ; calculateSpan ( price , n , S ) ; printArray ( S ) ;