Maximize sum of K corner elements in Array | Java program to maximize the sum of K elements in the array by taking only corner elements ; Function to return maximum sum ; Base case ; Pick the start index ; Pick the end index ; Recursive function call ; Return the final answer ; Function to find the maximized sum ; Driver code
import java . util . * ; class GFG { static int maxSum ( int arr [ ] , int K , int start , int end , int max_sum ) { if ( K == 0 ) return max_sum ; int max_sum_start = max_sum + arr [ start ] ; int max_sum_end = max_sum + arr [ end ] ; int ans = Math . max ( maxSum ( arr , K - 1 , start + 1 , end , max_sum_start ) , maxSum ( arr , K - 1 , start , end - 1 , max_sum_end ) ) ; return ans ; } static void maximizeSum ( int arr [ ] , int K , int n ) { int max_sum = 0 ; int start = 0 ; int end = n - 1 ; System . out . print ( maxSum ( arr , K , start , end , max_sum ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 4 , 4 , 8 , 12 , 3 , 2 , 9 } ; int K = 3 ; int n = arr . length ; maximizeSum ( arr , K , n ) ; } }