DIY: Find Maximum Sum from Either End of an Array
Solve the interview question "Find Maximum Sum from Either End of an Array" in this lesson.
We'll cover the following
Problem statement
For this challenge, you are given an array of integers, nums
, and a positive integer, k
. Your job is to find the maximum sum obtained from the k
elements of the array. However, there is one condition: you cannot pick k
elements at random. You can only remove elements one by one from either side of the array to add to the total sum.
The value of
k
will always be less than or equal to the length of thenums
array.
Input
The inputs will be an array of integers called nums
and a positive integer k. The following is an example of input:
{5,2,3,4,1,6,1}
3
Output
The output will be the maximum sum that can be obtained from k
elements of the array by picking the elements from either side of the array one-by-one. The inputs mentioned-above will give the following output:
12
We obtained the output
12
because we picked out three numbers in the order:5
(from the start),1
(from the end), and6
(from the end).
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.