VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-sum-of-k-elements-in-array-by-taking-only-corner-elements/

⇱ Maximize sum of K corner elements in Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize sum of K corner elements in Array

Last Updated : 12 Jul, 2025

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:  


Output: 
21

 

Time Complexity: O(2^N)

Auxiliary Space: O(N)

Efficient Approach: To solve the problem more efficiently we will implement Sliding Window concept. 

  • Initialize two integers with 0, curr_points and max_points to represents current points and maximum points respectively.
  • Now, iterate over K elements one by one from the beginning and form the window of size K, also update the value of curr_points by curr_points + arr[i] and max_points with the value of curr_points.
  • After that in each step, take one element from the end of the array and remove the rightmost element from the previously selected window with beginning elements where the window size always remains K. Update the values for curr_points and max_points accordingly. At last, we have K elements from the end of the array, and max_points contains the required result that has to be returned.

Let us look at the image below to understand it better:

👁 Image


Below is the implementation of the above approach: 


Output
21

Time Complexity: O(N), where N is size of the array.
Auxiliary Space Complexity: O(1).

Comment
Article Tags:
Article Tags: