Return the actual subarray elements that produce the maximum subarray sum.
Problem Statement
Examples
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: [4, -1, 2, 1]
Explanation: Combining the input according to Print subarray with maximum subarray sum (extended version of above problem) logic yields [4, -1, 2, 1].
Input: nums = [1]
Output: [1]
Explanation: Combining the input according to Print subarray with maximum subarray sum (extended version of above problem) logic yields [1].
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
By maintaining start and end pointers alongside the Kadane accumulation, whenever a new maximum sum is discovered, we update the boundary range [ansStart, ansEnd]. At the end, we slice and return the subarray.
Step-by-Step Approach
- Track
maxSum = -Infinity,currentSum = 0,start = 0,ansStart = 0,ansEnd = 0. - For each index
i: - If
currentSum === 0, markstart = i. - Add
nums[i]tocurrentSum. - If
currentSum > maxSum, updatemaxSum = currentSum,ansStart = start,ansEnd = i. - If
currentSum < 0, resetcurrentSum = 0. - Return
nums.slice(ansStart, ansEnd + 1).
Optimal Implementation (JavaScript)
function maxSubarrayElements(nums) {
let maxSum = -Infinity;
let currentSum = 0;
let start = 0, ansStart = 0, ansEnd = 0;
for (let i = 0; i < nums.length; i++) {
if (currentSum === 0) start = i;
currentSum += nums[i];
if (currentSum > maxSum) {
maxSum = currentSum;
ansStart = start;
ansEnd = i;
}
if (currentSum < 0) {
currentSum = 0;
}
}
return nums.slice(ansStart, ansEnd + 1);
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- All negative elements: returns the single least negative element.
- All positive elements: returns the entire array.
- Single element array: returns the array itself.