Maximum Subarray Sum [Solution]
Below is a Python implementation of the max_subarray_sum
function to find the maximum sum of a contiguous subarray:
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
"""
Find the maximum sum of a contiguous subarray in the given array.
Parameters:
- nums: List of integers.
Returns:
- int: Maximum sum of a contiguous subarray.
"""
if not nums:
return 0
max_sum = current_sum = nums[0]
for num in nums[1:]:
# Compare the current number with the sum of the previous subarray
current_sum = max(num, current_sum + num)
# Update the maximum sum if the current subarray is larger
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage:
nums1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
result1 = max_subarray_sum(nums1)
print(result1) # Output: 6
nums2 = [1]
result2 = max_subarray_sum(nums2)
print(result2) # Output: 1
nums3 = [5, 4, -1, 7, 8]
result3 = max_subarray_sum(nums3)
print(result3) # Output: 23
This solution uses Kadane’s algorithm to efficiently find the maximum sum of a contiguous subarray.
Time Complexity:
The time complexity is O(n)
,
where n
is the length of the input array.
Space Complexity:
The space complexity is O(1)
since no additional space is used.