Maximize array elements upto given number | Java code to find maximum value of number obtained by using array elements recursively . ; 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
import java . io . * ; import java . lang . * ; public class GFG { static int ans ; static void findMaxValUtil ( int [ ] arr , int n , int num , int maxLimit , int 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 ) ; } } static int findMaxVal ( int [ ] arr , int n , int num , int maxLimit ) { int ind = 0 ; findMaxValUtil ( arr , n , num , maxLimit , ind ) ; return ans ; } public static void main ( String args [ ] ) { int num = 1 ; int [ ] arr = { 3 , 10 , 6 , 4 , 5 } ; int n = arr . length ; int maxLimit = 15 ; System . out . print ( findMaxVal ( arr , n , num , maxLimit ) ) ; } }