Maximum Subarray Sum with a Length Cap
Company: Oracle
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Compute the maximum sum of a nonempty contiguous subarray whose length cannot exceed a given cap. The prompt fixes negative-only behavior, integer-width expectations, and two exact examples for later cross-language console verification.
Read the full Oracle Software Engineer interview experience this question came from
Constraints
- 1 <= len(nums) <= 200,000
- 1 <= k <= len(nums)
- -10^9 <= nums[i] <= 10^9
- The selected contiguous subarray must be nonempty.
- The result may exceed 32-bit signed integer range.
Examples
Input: ([2, -1, 3, 4, -5], 3)
Expected Output: 7
Explanation: The length-two subarray [3, 4] has the maximum sum 7.
Input: ([-4, -2, -7], 2)
Expected Output: -2
Explanation: The nonempty requirement selects the single value -2.
Hints
- Express every subarray sum as a difference of two prefix sums.
- For each right boundary, maintain the minimum eligible prefix sum from the previous k positions.