The Stock Span Problem | C # program for a linear time solution for stock span problem without using stack ; 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
using System ; public class GFG { static void calculateSpan ( int [ ] A , int n , int [ ] ans ) { ans [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { int counter = 1 ; while ( ( i - counter ) >= 0 && A [ i ] >= A [ i - counter ] ) { counter += ans [ i - counter ] ; } ans [ i ] = counter ; } } static void printArray ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } 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 , n ) ; } }