Find the maximum subarray sum.
MediumGiven 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.
Our solution for finding the maximum subarray sum processes the input array by iterating through it while maintaining two variables: max_current and max_global. The max_current variable keeps track of the maximum sum of the subarray ending at the current position, while max_global stores the maximum sum encountered so far.
For each element in the array, we update max_current by taking the maximum of the current element alone or the sum of the current element and max_current. This decision ensures that max_current always holds the maximum sum of the subarray that ends at the current element. We then update max_global to be the maximum of max_global and max_current.
If the input array is empty, the function returns 0 since there are no subarrays to consider.
This approach uses a simple iteration and a couple of variables, making it both straightforward and efficient.
Time Complexity: The solution has a time complexity of O(n), where n is the number of elements in the array. This is because we iterate through the array once, performing constant-time operations (comparison and addition) for each element.
Space Complexity: The solution uses O(1) space since it only requires a fixed amount of extra space for the max_current and max_global variables, regardless of the input size. This makes the solution very efficient in terms of space usage.
Interview experiences
4 sharedRelated questions
Find the maximum subarray productFind the minimum sum subarray of size k.Find the maximum product subarray in a given array.Related courses

















