Queries to check if array elements from indices [ L , R ] forms an Arithmetic Progression or not | Java program for the above approach ; Function to check if the given range of queries form an AP or not in the given array arr [ ] ; Stores length of the longest subarray forming AP for every array element ; Iterate over the range [ 0 , N ] ; Stores the index of the last element of forming AP ; Iterate until the element at index ( j , j + 1 ) forms AP ; Increment j by 1 ; Traverse the current subarray over the range [ i , j - 1 ] ; Update the length of the longest subarray at index k ; Update the value of i ; Traverse the given queries ; Print the result ; Otherwise ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findAPSequence ( int arr [ ] , int N , int Q [ ] [ ] , int M ) { int dp [ ] = new int [ N + 5 ] ; for ( int i = 0 ; i + 1 < N ; ) { int j = i + 1 ; while ( j + 1 < N && arr [ j + 1 ] - arr [ j ] == arr [ i + 1 ] - arr [ i ] ) j ++ ; for ( int k = i ; k < j ; k ++ ) { dp [ k ] = j - k ; } i = j ; } for ( int i = 0 ; i < M ; i ++ ) { if ( dp [ Q [ i ] [ 0 ] ] >= Q [ i ] [ 1 ] - Q [ i ] [ 0 ] ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 7 , 6 , 5 , 4 , 1 } ; int Q [ ] [ ] = { { 0 , 3 } , { 3 , 4 } , { 2 , 4 } } ; int N = arr . length ; int M = Q . length ; findAPSequence ( arr , N , Q , M ) ; } }