Check if the sum of a subarray within a given range is a perfect square or not | Java implementation of the above approach ; Function to calculate the square root of the sum of a subarray in a given range ; Calculate the sum of array elements within a given range ; Finding the square root ; If a perfect square is found ; Reduce the search space if the value is greater than sum ; Reduce the search space if the value if smaller than sum ; Driver Code ; Given Array ; Given range ; Function Call
import java . util . * ; class GFG { static int checkForPerfectSquare ( int [ ] arr , int i , int j ) { int mid , sum = 0 ; for ( int m = i ; m <= j ; m ++ ) { sum += arr [ m ] ; } int low = 0 , high = sum / 2 ; while ( low <= high ) { mid = low + ( high - low ) / 2 ; if ( mid * mid == sum ) { return mid ; } else if ( mid * mid > sum ) { high = mid - 1 ; } else { low = mid + 1 ; } } return - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 19 , 33 , 48 , 90 , 100 } ; int L = 1 , R = 3 ; System . out . print ( checkForPerfectSquare ( arr , L , R ) ) ; } }