Minimum removal of elements from end of an array required to obtain sum K | Function to find the smallest array that can be removed from the ends of an array to obtain sum K ; Sum of complete array ; If given number is greater than sum of the array ; If number is equal to the sum of array ; tar is sum of middle subarray ; Find the longest subarray with sum equal to tar ; If there is no subarray with sum equal to tar ; Driver Code ; Given Array ; Given target sum
def minSizeArr ( A , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT if ( K > sum ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE return NEW_LINE DEDENT if ( K == sum ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT tar = sum - K NEW_LINE um = { } NEW_LINE um [ 0 ] = - 1 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE cur = 0 NEW_LINE maxi = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur += A [ i ] NEW_LINE if ( ( cur - tar ) in um and ( i - um [ cur - tar ] ) > maxi ) : NEW_LINE INDENT maxi = i - um [ cur - tar ] NEW_LINE right = i NEW_LINE left = um [ cur - tar ] NEW_LINE DEDENT if ( cur not in um ) : NEW_LINE INDENT um [ cur ] = i NEW_LINE DEDENT DEDENT if ( maxi == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( left + 1 ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT for i in range ( right ) : NEW_LINE INDENT print ( A [ N - i - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE A = [ 3 , 2 , 1 , 1 , 1 , 1 , 3 ] NEW_LINE K = 10 NEW_LINE minSizeArr ( A , N , K ) NEW_LINE DEDENT