Google Interview Onsite (University Grad – 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

int function(int arr[])
{
    Int n = arr.size();
    Int lpref[n], rpref[n]; // for left and right prefix sum
    Lpref[0] = arr[0], 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;
}

chevron_right



Write your Interview Experience or mail it to contribute@geeksforgeeks.org

My Personal Notes arrow_drop_up

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.