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:

  1. Initialization:

    • current_sum: Keeps track of the sum of the current subarray.
    • max_sum: Stores the maximum sum encountered so far.
  2. Iteration:

    • The code iterates through each element (num) in the nums array.
    • For each element, it calculates the current_sum by comparing the following:
      • num: The current element alone.
      • current_sum + num: The sum of the previous subarray and the current element.
    • The max_sum is updated by comparing the current maximum sum (max_sum) with the current_sum.
  3. Return:

    • The function returns the final max_sum, representing the largest sum of a contiguous subarray within the input array.

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.

Python: Finding the Maximum Subarray Sum

原文地址: http://www.cveoy.top/t/topic/ZS8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录