Python: Finding the Maximum Subarray Sum
Certainly! Here's the implementation of the maxSubArray function, which utilizes Kadane's algorithm to efficiently find the maximum sum of a contiguous subarray within a given integer array.
import numpy as np
def maxSubArray(nums):
current_sum = 0
max_sum = nums[0]
for num in nums:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
Explanation:
-
Initialization:
current_sum: Keeps track of the sum of the current subarray.max_sum: Stores the maximum sum encountered so far.
-
Iteration:
- The code iterates through each element (
num) in thenumsarray. - For each element, it calculates the
current_sumby comparing the following:num: The current element alone.current_sum + num: The sum of the previous subarray and the current element.
- The
max_sumis updated by comparing the current maximum sum (max_sum) with thecurrent_sum.
- The code iterates through each element (
-
Return:
- The function returns the final
max_sum, representing the largest sum of a contiguous subarray within the input array.
- The function returns the final
Test Cases:
assert maxSubArray(np.array([-2, 1, -3, 4, -1, 2, 1, -5, 4])) == 6
assert maxSubArray(np.array([-2])) == -2
These assertions ensure that the function correctly identifies the maximum subarray sum for various input arrays. If the assertions pass without raising an AssertionError, it confirms that the implementation of the maxSubArray function is working as intended.
原文地址: http://www.cveoy.top/t/topic/ZS8 著作权归作者所有。请勿转载和采集!