Length of longest subarray of length at least 2 with maximum GCD | C # program for the above approach ; Function to calculate GCD of two numbers ; Function to find maximum size subarray having maximum GCD ; Base case ; Let the maximum GCD be 1 initially ; Loop through array to find maximum GCD of subarray with size 2 ; Traverse the array ; Is a multiple of k , increase cnt ; Else update maximum length with consecutive element divisible by k Set cnt to 0 ; Update the maxLength ; Return the maxLength ; Driver code ; Function call
using System ; using System . Collections . Generic ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int maximumGcdSubarray ( int [ ] arr , int n ) { if ( n == 1 ) return 0 ; int k = 1 ; for ( int i = 1 ; i < n ; i ++ ) { k = Math . Max ( k , gcd ( arr [ i ] , arr [ i - 1 ] ) ) ; } int cnt = 0 ; int maxLength = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { cnt ++ ; } else { maxLength = Math . Max ( maxLength , cnt ) ; cnt = 0 ; } } maxLength = Math . Max ( maxLength , cnt ) ; return maxLength ; } static void Main ( ) { int [ ] arr = { 18 , 3 , 6 , 9 } ; int n = arr . Length ; Console . WriteLine ( maximumGcdSubarray ( arr , n ) ) ; } }