Maximum Sum from Array Ends
Problem statement
Choose exactly k elements from an integer array. Each chosen element must be taken from the current left or right end. Return the largest possible sum.
Equivalently, choose a prefix of length l and a suffix of length k-l, for some 0 <= l <= k. The chosen portions cannot overlap.
For this exercise, assume signed values and permit k=0, which returns 0. Return a 64-bit integer sum.
Function
maxSumFromEnds(nums: int[], k: int) → longExamples
Example 1
nums = [5,4,3,10,1,1000,2]k = 2return = 1002The best two picks are 1000 and 2 from the right.
Example 2
nums = [5,4,3,10,1,1000,2]k = 3return = 1007Choose 5 from the left and 1000,2 from the right.
Example 3
nums = [5,4,3,10,1,1000,2]k = 4return = 1013Taking 10,1,1000,2 from the right beats the reported 1011 combination. The author acknowledged this correction.
Constraints
- For this exercise, assume
0 <= nums.length <= 10^5and0 <= k <= nums.length. -10^6 <= nums[i] <= 10^6.