Maximum contiguous decreasing sequence obtained by removing any one element | Java program to find maximum length of decreasing sequence by removing at most one element ; Function to find the maximum length ; Initialise maximum length to 1 ; Initialise left [ ] to find the length of decreasing sequence from left to right ; Initialise right [ ] to find the length of decreasing sequence from right to left ; Initially store 1 at each index of left and right array ; Iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the right array ; Store the length of longest continuous decreasing sequence in maximum ; Iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the left array ; Check if we can obtain a longer decreasing sequence after removal of any element from the array arr [ ] with the help of left [ ] & right [ ] ; Return maximum length of sequence ; Driver code ; Function calling
class GFG { static int maxLength ( int [ ] a , int n ) { int maximum = 1 ; int left [ ] = new int [ n ] ; int right [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = 1 ; right [ i ] = 1 ; } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( a [ i ] > a [ i + 1 ] ) { right [ i ] = right [ i + 1 ] + 1 ; } maximum = Math . max ( maximum , right [ i ] ) ; } for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] < a [ i - 1 ] ) { left [ i ] = left [ i - 1 ] + 1 ; } } if ( n > 2 ) { for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( a [ i - 1 ] > a [ i + 1 ] ) { maximum = Math . max ( maximum , left [ i - 1 ] + right [ i + 1 ] ) ; } } } return maximum ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 7 , 3 , 5 , 2 , 9 } ; int n = arr . length ; System . out . println ( maxLength ( arr , n ) ) ; } }