The Stock Span Problem | Java implementation for brute force method to calculate stock span values ; 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 program to test above functions ; Fill the span values in array S [ ] ; print the calculated span values
import java . util . Arrays ; class GFG { static void calculateSpan ( int price [ ] , int n , int S [ ] ) { S [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { S [ i ] = 1 ; for ( int j = i - 1 ; ( j >= 0 ) && ( price [ i ] >= price [ j ] ) ; j -- ) S [ i ] ++ ; } } static void printArray ( int arr [ ] ) { System . out . print ( Arrays . toString ( arr ) ) ; } public static void main ( String [ ] args ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = price . length ; int S [ ] = new int [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S ) ; } }