Longest subarray forming a Geometic Progression ( GP ) | Java program to implement the above approach ; Function to return the length of the longest subarray forming a GP in a sorted array ; Base Case ; Stores the length of GP and the common ratio ; Stores the maximum length of the GP ; Traverse the array ; Check if the common ratio is valid for GP ; If the current common ratio is equal to previous common ratio ; Increment the length of the GP ; Store the max length of GP ; Otherwise ; Update the common ratio ; Update the length of GP ; Store the max length of GP ; Update the length of GP ; Store the max length of GP ; Return the max length of GP ; Driver code ; Given array ; Length of the array ; Function call
import java . io . * ; class GFG { static int longestGP ( int A [ ] , int N ) { if ( N < 2 ) return N ; int length = 1 , common_ratio = 1 ; int maxlength = 1 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i + 1 ] % A [ i ] == 0 ) { if ( A [ i + 1 ] / A [ i ] == common_ratio ) { length = length + 1 ; maxlength = Math . max ( maxlength , length ) ; } else { common_ratio = A [ i + 1 ] / A [ i ] ; length = 2 ; } } else { maxlength = Math . max ( maxlength , length ) ; length = 1 ; } } maxlength = Math . max ( maxlength , length ) ; return maxlength ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 7 , 14 , 28 , 56 , 89 } ; int N = arr . length ; System . out . println ( longestGP ( arr , N ) ) ; } }