Content deleted Content added
→No empty subarrays admitted: nonempty |
I'm trying to be reasonable, and not condescending like others. It's wrong to place a src change and say it's broken for this scenario when we can easily have it work for all the scenarios. There was never a misunderstanding. Empty array will work as well. More changes will be needed as there are other fallacies I'm noticing. Tag: Reverted |
||
Line 58:
In the Python code below, <math>A[j]</math> is expressed as <code>x</code>, with the index <math>j</math> left implicit.
}}
is the maximum over all <math>i \in \{ 1,\ldots, j \}</math> of the sum <math>A[i]+\cdots+A[j]</math>. To extend the latter maximum to cover also the case <math>i=j+1</math>, it is sufficient to consider also the empty subarray <math>A[j+1 \; \ldots \; j]</math>. This is done in line
Thus, the problem can be solved with the following code,{{sfn|Bentley|1989|p=74}}{{sfn|Gries|1982|p=211}} expressed here in [[Python (programming language)|Python]]:
Line 65:
def max_subarray(numbers):
"""Find the largest sum of any contiguous subarray."""
"""Return nothing when an empty array is passed."""
current_sum = 0▼
return None
"""Setting initial values to max negative in Python (-2 ** 31)"""
best_sum = (-2 ** 31)
for x in numbers:
current_sum = max(
best_sum = max(best_sum, current_sum)
return best_sum
</syntaxhighlight>
The code implementation assumes a max integer value (positive and negative) of 2,147,483,648.
This algorithm calculates the maximum subarray ending at each position from the maximum subarray ending at the previous position, so it can be viewed as a trivial case of [[dynamic programming]].
===Computing the best subarray's position===
|