Subarray whose absolute sum is closest to K | Java code to find sub - array whose sum shows the minimum deviation ; Starting index , ending index , Deviation ; Iterate i and j to get all subarrays ; Found sub - array with less sum ; Exactly same sum ; Driver Code ; Array to store return values
class GFG { public static int [ ] getSubArray ( int [ ] arr , int n , int K ) { int i = - 1 ; int j = - 1 ; int currSum = 0 ; int [ ] result = { i , j , Math . abs ( K - Math . abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ; int currDev = Math . abs ( K - Math . abs ( currSum ) ) ; if ( currDev < result [ 2 ] ) { result [ 0 ] = i ; result [ 1 ] = j ; result [ 2 ] = currDev ; } if ( currDev == 0 ) return result ; } } return result ; } public static void main ( String [ ] args ) { int [ ] arr = { 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 } ; int n = arr . length ; int K = 50 ; int [ ] ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == - 1 ) { System . out . println ( " The ▁ empty ▁ array ▁ " + " shows ▁ minimum ▁ Deviation " ) ; } else { for ( int i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } } }