Maximum Sum from Array Ends
Updated
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.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Maximum Earnings Across WarehousesAmazon · ONSITE INTERVIEW
- Shortest Window with Required CountsOracle · ONSITE INTERVIEWOracle interview questions
- Count Zero Request ServersSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Longest Binary Subarray With at Most K OnesLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Max Consecutive Ones IIIMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Longest Continuous Subarray Within an Absolute-Difference LimitUber · ONSITE INTERVIEWUber interview questions
- Sliding-Window Rate LimiterSnowflake · ONSITE INTERVIEWSnowflake interview questions
- Count Equal Code Pairs Within Distance KInfosys · ONSITE INTERVIEWInfosys interview questions
- Maximize Element FrequencyGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Longest Subarray with At Most Two Distinct ValuesMoody's Investors Service · ONSITE INTERVIEW