Subarray whose absolute sum is closest to K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int * getSubArray ( int arr [ ] , int n , int K ) { int i = -1 ; int j = -1 ; int currSum = 0 ; int * result = new int [ 3 ] { i , j , abs ( K - abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ; int currDev = abs ( K - abs ( currSum ) ) ; if ( currDev < result [ 2 ] ) { result [ 0 ] = i ; result [ 1 ] = j ; result [ 2 ] = currDev ; } if ( currDev == 0 ) return result ; } } return result ; } int main ( ) { int arr [ 8 ] = { 15 , -3 , 5 , 2 , 7 , 6 , 34 , -6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 50 ; int * ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == -1 ) { cout << " The ▁ empty ▁ array ▁ shows ▁ " << " minimum ▁ Deviation " ; } else { for ( int i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) cout << arr [ i ] << " ▁ " ; } return 0 ; }