Related Articles
• 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;``}`

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course. In case you are prepared, test your skills using TCS, Wipro, Amazon and Microsoft Test Serieses.

My Personal Notes arrow_drop_up