• Difficulty Level : Medium
• Last Updated : 21 Apr, 2020

Question :Given an array having 2n elements you can choose n elements from either end of the array such that the values obtained result in maximum sum.

Examples:

```Input : 1 3 100 25 20 4
Output : 103
```

Approach: Initially, I tried recursive approach by showing both possibilities of an element that it can either be included or excluded, but he told to optimize it and I came up with prefix sum approach.
Idea: The main idea behind the prefix sum approach was if we select ‘x’ elements from left we can select ‘n-x’ elements from the right.

 `int` `function(``int` `arr[])``{``    ``Int n = arr.size();``    ``Int lpref[n], rpref[n]; ``// for left and right prefix sum``    ``Lpref = arr, rpref[n - 1] = arr[n - 1];``    ``For(``int` `i = 1; i < n; i++)``    ``{``        ``Lpref[i] = Lpref[i - 1] + arr[i];``    ``}``    ``For(``int` `i = n - 2; i >= 0; i--)``    ``{``        ``rpref[i] = rpref[i + 1] + arr[i];``    ``}``    ``Int maxm = INT_MIN, m = n / 2;``    ``For(``int` `i = 0; i < m - 1; i++)``    ``{``maxm =max(maxm, lpref[i]+rpref[n-1-i];``    ``}``    ``maxm = max(maxm, lpref[m - 1]);``    ``maxm = max(maxm, rpref[n - m]);``    ``return` `maxm;``}`

My Personal Notes arrow_drop_up