Check if any valid sequence is divisible by M | Java program for the above approach ; Function to check if any valid sequence is divisible by M ; Declare mod array ; Calculate the mod array ; Check if sum is divisible by M ; Check if sum is not divisible by 2 ; Remove the first element from the ModArray since it is not possible to place minus on the first element ; Decrease the size of array ; Sort the array ; Loop until the pointer cross each other ; Check if sum becomes equal ; Increase and decrease the pointer accordingly ; Driver code ; Function call
import java . util . * ; class GFG { static void func ( int n , int m , int [ ] A ) { Vector < Integer > ModArray = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) ModArray . add ( 0 ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ModArray . set ( i , A [ i ] % m ) ; sum += ( ( int ) ModArray . get ( i ) ) ; } sum = sum % m ; if ( sum % m == 0 ) { System . out . println ( " True " ) ; return ; } if ( sum % 2 != 0 ) { System . out . println ( " False " ) ; } else { ModArray . remove ( 0 ) ; int i = 0 ; int j = ModArray . size ( ) - 1 ; Collections . sort ( ModArray ) ; sum = sum / 2 ; int i1 , i2 ; while ( i <= j ) { int s = ( int ) ModArray . get ( i ) + ( int ) ModArray . get ( j ) ; if ( s == sum ) { i1 = i ; i2 = j ; System . out . println ( " True " ) ; break ; } else if ( s > sum ) j -- ; else i ++ ; } } } public static void main ( String args [ ] ) { int m = 2 ; int [ ] a = { 1 , 3 , 9 } ; int n = a . length ; func ( n , m , a ) ; } }