Longest Non | Java program for the above approach ; Function to find the length of the longest non - increasing subsequence ; Stores the prefix and suffix count of 1 s and 0 s respectively ; Initialize the array ; Store the number of '1' s up to current index i in pre ; Find the prefix sum ; If the current element is '1' , update the pre [ i ] ; Store the number of '0' s over the range [ i , N - 1 ] ; Find the suffix sum ; If the current element is '0' , update post [ i ] ; Stores the maximum length ; Find the maximum value of pre [ i ] + post [ i ] ; Return the answer ; Driver Code
class GFG { static int findLength ( String str , int n ) { int pre [ ] = new int [ n ] ; int post [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { pre [ i ] = 0 ; post [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( i != 0 ) { pre [ i ] += pre [ i - 1 ] ; } if ( str . charAt ( i ) == '1' ) { pre [ i ] += 1 ; } } for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i != n - 1 ) post [ i ] += post [ i + 1 ] ; if ( str . charAt ( i ) == '0' ) post [ i ] += 1 ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = Math . max ( ans , pre [ i ] + post [ i ] ) ; } return ans ; } public static void main ( String [ ] args ) { String S = "0101110110100001011" ; System . out . println ( findLength ( S , S . length ( ) ) ) ; } }