Maximize array elements upto given number | variable to store maximum value that can be obtained . ; If entire array is traversed , then compare current value in num to overall maximum obtained so far . ; Case 1 : Subtract current element from value so far if result is greater than or equal to zero . ; Case 2 : Add current element to value so far if result is less than or equal to maxLimit . ; def to find maximum possible value that can be obtained using array elements and given number . ; variable to store current index position . ; call to utility def to find maximum possible value that can be obtained . ; Driver code
ans = 0 ; NEW_LINE def findMaxValUtil ( arr , n , num , maxLimit , ind ) : NEW_LINE INDENT global ans NEW_LINE if ( ind == n ) : NEW_LINE INDENT ans = max ( ans , num ) NEW_LINE return NEW_LINE DEDENT if ( num - arr [ ind ] >= 0 ) : NEW_LINE INDENT findMaxValUtil ( arr , n , num - arr [ ind ] , maxLimit , ind + 1 ) NEW_LINE DEDENT if ( num + arr [ ind ] <= maxLimit ) : NEW_LINE INDENT findMaxValUtil ( arr , n , num + arr [ ind ] , maxLimit , ind + 1 ) NEW_LINE DEDENT DEDENT def findMaxVal ( arr , n , num , maxLimit ) : NEW_LINE INDENT global ans NEW_LINE ind = 0 NEW_LINE findMaxValUtil ( arr , n , num , maxLimit , ind ) NEW_LINE return ans NEW_LINE DEDENT num = 1 NEW_LINE arr = [ 3 , 10 , 6 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE maxLimit = 15 NEW_LINE print ( findMaxVal ( arr , n , num , maxLimit ) ) NEW_LINE