Maximum Subarray Sum with Length at Most K
Updated
Problem statement
Given an integer array nums and an integer k, return the maximum sum of a non-empty contiguous subarray whose length is at most k.
The array may contain negative values, so the answer may be negative.
Function
maxSubarrayAtMostK(nums: int[], k: int) → longExamples
Example 1
nums = [-2,3,-1,5,-6]k = 3return = 7The length-three subarray [3, -1, 5] has sum 7, which is maximal.
Example 2
nums = [-5,-2,-7]k = 2return = -2The subarray must be non-empty, so the best choice is the single value -2.
Constraints
1 <= nums.length <= 2 * 10^51 <= k <= nums.length-10^9 <= nums[i] <= 10^9- The result fits in a signed 64-bit integer.
More Oracle Onsite Interview questions
- Course ScheduleONSITE INTERVIEW · Seen Nov 2026
- Shortest Subarray with Sum at Least KONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Minimum Meeting RoomsONSITE INTERVIEW · Seen Nov 2026
- Shortest Window with Required CountsONSITE INTERVIEW · Seen Nov 2026
- Maximum Subarray Sum with One DeletionONSITE INTERVIEW · Seen Nov 2026
- Shortest Deletion for Distinct CharactersONSITE INTERVIEW · Seen Nov 2026
- Count Dropped Rate-Limited RequestsONSITE INTERVIEW · Seen Nov 2026
- Design Authentication ManagerONSITE INTERVIEW · Seen Oct 2026
- Maximum Bouquet ValueONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Minimum Size Subarray Sum With NegativesTekion · ONSITE INTERVIEWTekion interview questions
- Shortest Subarray with Sum at Least KApple · ONSITE INTERVIEWApple interview questions
- Shortest Subarray with Sum at Least KGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- Shortest Subarray with Sum at Least KGoogle · PHONE SCREENGoogle interview questions
- Profit AnalysisVirtu Financial · OAVirtu Financial interview questions
- Sliding Window MaximumAmazon · ONSITE INTERVIEW
- Sliding Window MaximumPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Sliding Window MaximumBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Number of Submatrices That Sum to TargetWhatNot · ONSITE INTERVIEWWhatNot interview questions
- Subarray Sum Equals KServiceNow · ONSITE INTERVIEWServiceNow interview questions