![]() |
VOOZH | about |
Given an array arr[] and an integer K, the task is to find the maximize the sum of K elements in the Array by taking only corner elements.
A corner element is an element from the start of the array or from the end of the array.
Examples:
Input: arr[] = {8, 4, 4, 8, 12, 3, 2, 9}, K = 3
Output: 21
Explanation:
The optimal strategy is to pick the elements from the array is, two indexes from the beginning and one index from the end. All other possible choice will yield lesser sum. Hence, arr[0] + arr[1] + arr[7] = 21.Input: arr[] = {2, 1, 14, 6, 4, 3}, K = 3
Output: 17
Explanation:
We will get the maximum sum by picking first three elements from the array. Hence, Optimal choice is: arr[0] + arr[1] + arr[2] = 17
Naive Approach: The idea is to use Recursion. As we can only take a start or end index value hence initialize two variables and take exactly K steps and return the maximum sum among all the possible combinations. The recursive approach has exponential complexity due to its overlapping subproblem and optimal substructure property.
Below is the implementation of the above approach:
21
Time Complexity: O(2^N)
Auxiliary Space: O(N)
Efficient Approach: To solve the problem more efficiently we will implement Sliding Window concept.
Let us look at the image below to understand it better:
Below is the implementation of the above approach:
21
Time Complexity: O(N), where N is size of the array.
Auxiliary Space Complexity: O(1).