Divide array into two parts with equal sum according to the given constraints | Java implementation of the approach ; Function that checks if the given conditions are satisfied ; To store the prefix sum of the array elements ; Sort the array ; Compute the prefix sum array ; Maximum element in the array ; Variable to check if there exists any number ; Stores the index of the largest number present in the array smaller than i ; Stores the index of the smallest number present in the array greater than i ; Find index of smallest number greater than i ; Find index of smallest number greater than i ; If there exists a number ; If no such number exists print no ; Driver code
import java . util . * ; class GFG { static void IfExists ( int arr [ ] , int n ) { int sum [ ] = new int [ n ] ; Arrays . sort ( arr ) ; sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) sum [ i ] = sum [ i - 1 ] + arr [ i ] ; int max = arr [ n - 1 ] ; boolean flag = false ; for ( int i = 1 ; i <= max ; i ++ ) { int findex = 0 ; int lindex = 0 ; int l = 0 ; int r = n - 1 ; while ( l <= r ) { int m = ( l + r ) / 2 ; if ( arr [ m ] < i ) { findex = m ; l = m + 1 ; } else r = m - 1 ; } l = 1 ; r = n ; flag = false ; while ( l <= r ) { int m = ( r + l ) / 2 ; if ( arr [ m ] > i ) { lindex = m ; r = m - 1 ; } else l = m + 1 ; } if ( sum [ findex ] == sum [ n - 1 ] - sum [ lindex - 1 ] ) { flag = true ; break ; } } if ( flag ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 2 , 5 } ; int n = arr . length ; IfExists ( arr , n ) ; } }