To solve this problem, we need to find the contiguous subarray (containing at least one element) with the largest sum in a given integer array. This is a classic problem that can be efficiently solved using Kadane's Algorithm, which runs in linear time (O(n)).
Approach (Kadane's Algorithm)
The key idea of Kadane's Algorithm is to keep track of two values as we iterate through the array:
- max_current: The maximum sum of the subarray ending at the current position. This is either the current element itself (if starting a new subarray here is better) or the sum of the current element plus the maximum subarray sum ending at the previous position.
- max_global: The maximum sum of any subarray encountered so far. This is updated whenever
max_currentexceeds its value.
Steps:
- Initialize
max_currentandmax_globalto the first element of the array (since we need at least one element in the subarray). - For each subsequent element:
- Update
max_currentto be the maximum of the current element or the sum ofmax_currentand the current element. - If
max_currentis greater thanmax_global, updatemax_global.
- Update
- Return
max_globalas the result.
Solution Code
def max_subarray_sum(arr):
max_current = max_global = arr[0]
for i in range(1, len(arr)):
max_current = max(arr[i], max_current + arr[i])
if max_current > max_global:
max_global = max_current
return max_global
Explanation
Let’s take an example to see how the algorithm works:
- Input:
[-2, 1, -3, 4, -1, 2, 1, -5, 4] - Iteration:
- Start with
max_current = -2,max_global = -2. - Next element
1:max_current = max(1, -2+1)=1,max_global =1. - Next
(-3):max_current = max(-3,1-3)= -2,max_global remains1. - Next
4:max_current = max(4, -2+4)=4,max_global=4. - Next
-1:max_current=4-1=3,global remains 4. - Next
2:3+2=5,global=5. - Next
1:5+1=6,global=6. - Next
-5:6-5=1,global remains 6. - Next
4:1+4=5,global remains6.
- Start with
Final result is 6 (sum of subarray [4,-1,2,1]).
This algorithm efficiently computes the desired result with a time complexity of (O(n)) and space complexity of (O(1)), making it optimal for large arrays. It handles all edge cases, including arrays with all negative numbers (returns the largest negative number). For example, input [-5,-3,-1] returns -1.
Note: The problem assumes the input array is non-empty (since it contains at least one element). If the array can be empty, we need to add a check for that (though the problem typically requires at least one element).
This solution is widely used in practice and is the standard approach for the maximum subarray problem. It is both time and space efficient, making it suitable for most real-world scenarios.
Keywords: Maximum Subarray, Kadane's Algorithm, Contiguous Subarray, Linear Time, Optimal Solution.
Application: This problem is common in coding interviews and has applications in fields like finance (e.g., finding the best time to buy/sell stocks, though that's a variation), signal processing, and data analysis.
The code provided is correct and should pass all test cases for the maximum subarray sum problem. It is written in Python, which is easy to understand and implement. The function takes an array as input and returns the maximum sum of any contiguous subarray.
For example, if you call max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]), it returns 6 as expected. Another test case: max_subarray_sum([1]) returns 1, max_subarray_sum([5,4,-1,7,8]) returns 23 (sum of all elements).
This solution is optimal and should handle all possible cases correctly. It is a must-know algorithm for any programmer or data scientist.
Final Answer: The code provided solves the maximum subarray sum problem using Kadane's Algorithm, which is the optimal approach for this problem. The function max_subarray_sum returns the correct result for all valid inputs.
The answer is the code itself, as it is the solution to the problem. However, if the problem expects a description, the explanation above covers it.
But according to the problem's context (since the assistant's response was the code), the correct answer is the code provided.
Final Code: The code as written is the correct solution. So the answer is the function max_subarray_sum as defined.
def max_subarray_sum(arr):
max_current = max_global = arr[0]
for i in range(1, len(arr)):
max_current = max(arr[i], max_current + arr[i])
if max_current > max_global:
max_global = max_current
return max_global
This is the correct solution to the maximum subarray sum problem.
def max_subarray_sum(arr):
max_current = max_global = arr[0]
for i in range(1, len(arr)):
max_current = max(arr[i], max_current + arr[i])
if max_current > max_global:
max_global = max_current
return max_global
作者声明:本文包含人工智能生成内容。