Maximize array elements upto given number | 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 maximum value that can be obtained . ; variable to store current index position . ; call to utility function to find maximum possible value that can be obtained . ; Driver code
< ? php function findMaxValUtil ( $ arr , $ n , $ num , $ maxLimit , $ ind , & $ ans ) { if ( $ ind == $ n ) { $ ans = max ( $ ans , $ num ) ; return ; } if ( $ num - $ arr [ $ ind ] >= 0 ) { findMaxValUtil ( $ arr , $ n , $ num - $ arr [ $ ind ] , $ maxLimit , $ ind + 1 , $ ans ) ; } if ( $ num + $ arr [ $ ind ] <= $ maxLimit ) { findMaxValUtil ( $ arr , $ n , $ num + $ arr [ $ ind ] , $ maxLimit , $ ind + 1 , $ ans ) ; } } function findMaxVal ( $ arr , $ n , $ num , $ maxLimit ) { $ ans = 0 ; $ ind = 0 ; findMaxValUtil ( $ arr , $ n , $ num , $ maxLimit , $ ind , $ ans ) ; return $ ans ; } $ num = 1 ; $ arr = array ( 3 , 10 , 6 , 4 , 5 ) ; $ n = count ( $ arr ) ; $ maxLimit = 15 ; echo ( findMaxVal ( $ arr , $ n , $ num , $ maxLimit ) ) ; ? >