Subarray whose absolute sum is closest to K | Python 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
def getSubArray ( arr , n , K ) : NEW_LINE INDENT i = - 1 NEW_LINE j = - 1 NEW_LINE currSum = 0 NEW_LINE result = [ i , j , abs ( K - abs ( currSum ) ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT currSum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT currSum += arr [ j ] NEW_LINE currDev = abs ( K - abs ( currSum ) ) NEW_LINE if ( currDev < result [ 2 ] ) : NEW_LINE INDENT result = [ i , j , currDev ] NEW_LINE DEDENT if ( currDev == 0 ) : NEW_LINE INDENT return result NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT arr = [ 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 50 NEW_LINE [ i , j , minDev ] = getSubArray ( arr , n , K ) NEW_LINE if ( i == - 1 ) : NEW_LINE INDENT print ( " The ▁ empty ▁ array ▁ shows ▁ minimum ▁ Deviation " ) NEW_LINE return 0 NEW_LINE DEDENT for i in range ( i , j + 1 ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT main ( ) NEW_LINE