Maximize array elements upto given number | variable to store maximum value that can be obtained . ; Utility function to find maximum possible value ; 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 . ; Function to find maximum possible value that can be obtained using array elements and given number . ; Variable to store current index position . ; Call to utility function to find maximum possible value that can be obtained . ; Driver code
let ans = 0 ; function findMaxValUtil ( arr , n , num , maxLimit , ind ) { if ( ind == n ) { ans = Math . max ( ans , num ) ; return ; } if ( num - arr [ ind ] >= 0 ) { findMaxValUtil ( arr , n , num - arr [ ind ] , maxLimit , ind + 1 ) ; } if ( num + arr [ ind ] <= maxLimit ) { findMaxValUtil ( arr , n , num + arr [ ind ] , maxLimit , ind + 1 ) ; } } function findMaxVal ( arr , n , num , maxLimit ) { let ind = 0 ; findMaxValUtil ( arr , n , num , maxLimit , ind ) ; return ans ; } let num = 1 ; let arr = [ 3 , 10 , 6 , 4 , 5 ] ; let n = arr . length ; let maxLimit = 15 ; document . write ( findMaxVal ( arr , n , num , maxLimit ) ) ;