Subarray whose absolute sum is closest to K | Javascript 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
function getSubArray ( arr , n , K ) { let i = - 1 ; let j = - 1 ; let currSum = 0 ; let 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 ] ; let 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 ; } let arr = [ 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 ] ; let n = arr . length ; let K = 50 ; let ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == - 1 ) { document . write ( " " + " " ) ; } else { for ( let i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) document . write ( arr [ i ] + " " ) ; }