Maximize sum of K corner elements in Array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 = max ( maxSum ( arr , K - 1 , start + 1 , end , max_sum_start ) , maxSum ( arr , K - 1 , start , end - 1 , max_sum_end ) ) ; return ans ; } void maximizeSum ( int arr [ ] , int K , int n ) { int max_sum = 0 ; int start = 0 ; int end = n - 1 ; cout << maxSum ( arr , K , start , end , max_sum ) ; } int main ( ) { int arr [ ] = { 8 , 4 , 4 , 8 , 12 , 3 , 2 , 9 } ; int K = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximizeSum ( arr , K , n ) ; return 0 ; }