To solve this problem, we need to find the maximum sum of a contiguous subarray within a given list of integers. This is a classic problem that can be efficiently solved using Kadane's Algorithm.
Approach: Kadane's Algorithm
The key idea behind Kadane's Algorithm is to keep track of two values as we iterate through the array:
- Current Maximum: The maximum sum of the subarray ending at the current position. This is calculated by choosing between starting a new subarray at the current element or continuing the previous subarray.
- Global Maximum: The highest value of the current maximum encountered so far.
Steps:
- Initialize both
current_maxandglobal_maxwith the first element of the array (since the array is non-empty). - Iterate from the second element to the end of the array:
- Update
current_maxto be the maximum of the current element or the sum ofcurrent_maxand the current element. - If
current_maxexceedsglobal_max, updateglobal_max.
- Update
- Return
global_maxas the result.
Solution Code
def maxSubArray(nums):
current_max = global_max = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
if current_max > global_max:
global_max = current_max
return global_max
Explanation
- Initialization: We start with
current_maxandglobal_maxset to the first element because the smallest possible subarray is a single element. - Iteration: For each subsequent element, we decide whether to start a new subarray (if the current element is larger than the sum of the current subarray plus the element) or continue the existing subarray.
- Update Global Maximum: Whenever the current subarray sum is larger than the global maximum, we update the global maximum to this value.
This approach runs in O(n) time complexity, where n is the length of the array, as we traverse the array exactly once. The space complexity is O(1) since we only use a few variables for tracking.
Examples:
- Input:
[-2,1,-3,4,-1,2,1,-5,4]→ Output:6(subarray[4,-1,2,1]). - Input:
[1]→ Output:1. - Input:
[5,4,-1,7,8]→ Output:23(sum of all elements).
This solution efficiently handles all cases, including arrays with all negative elements, by selecting the least negative element as the result.
Answer: The function maxSubArray as defined above.


作者声明:本文包含人工智能生成内容。