Skip to main content

Maximum Subarray Sum

MediumPremium

Given an array of integers nums, write a function maxSubarraySum to find the maximum sum of a contiguous subarray within the array and return that maximum sum. The subarray must be contiguous, meaning that the elements must appear consecutively in the original array.

Examples

Input: nums = [2, 3, -2, 4] Output: 7 Explanation: Maximum sum is 2 + 3 + (-2) + 4 = 7. Input: nums = [1, -1, -5, -4] Output: 1 Explanation: The maximum sum is 1, which is the single element with the highest value.

Can you come up with a solution with a O(n) time complexity?

Can you come up with a solution with a O(1) space complexity?