Minimum removal of elements from end of an array required to obtain sum K | Function to find the minimum number of elements required to be removed from the ends of an array to obtain a sum K ; Number of elements removed from the left and right ends of the array ; Sum of left and right subarrays ; No element is taken from left initially ; Start taking elements from right side ; ( left + 1 ) : Count of elements removed from the left ( N - right ) : Count of elements removed from the right ; If sum is greater than K ; If it is not possible to obtain sum K ; Driver Code ; Given Array ; Given target sum
def minSizeArr ( A , N , K ) : NEW_LINE INDENT leftTaken = N NEW_LINE rightTaken = N NEW_LINE leftSum = 0 NEW_LINE rightSum = 0 NEW_LINE for left in range ( - 1 , N ) : NEW_LINE INDENT if ( left != - 1 ) : NEW_LINE INDENT leftSum += A [ left ] NEW_LINE DEDENT rightSum = 0 NEW_LINE for right in range ( N - 1 , left , - 1 ) : NEW_LINE INDENT rightSum += A [ right ] NEW_LINE if ( leftSum + rightSum == K ) : NEW_LINE INDENT if ( leftTaken + rightTaken > ( left + 1 ) + ( N - right ) ) : NEW_LINE INDENT leftTaken = left + 1 NEW_LINE rightTaken = N - right NEW_LINE DEDENT break NEW_LINE DEDENT if ( leftSum + rightSum > K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( leftTaken + rightTaken <= N ) : NEW_LINE INDENT for i in range ( leftTaken ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT for i in range ( rightTaken ) : NEW_LINE INDENT print ( A [ N - i - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE 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