Maximum subarray problem: Difference between revisions

Content deleted Content added
Undid revision 1147103628 by David Eppstein (talk) Please stop reverting. The solution was incorrect. I've provided you the examples as to when it fails. This edit also contains max negative to make the solution more robust. I suggest placing the code into an editor and running examples. You're failing to see what's evidentiary.
Tag: Reverted
Undid revision 1147540473 by Onewikibarnes (talk) You still haven't even tried running the code as is, have you? It works correctly on your supposed incorrect examples. Stop messing with things you obviously aren't competent to understand.
Line 65:
def max_subarray(numbers):
"""Find the largest sum of any contiguous subarray."""
best_sum = 0
# Setting initial values to max negative in Python (-2 ** 31)
best_sumcurrent_sum = (-2 ** 31)0
current_sum = (-2 ** 31)
for x in numbers:
current_sum = max(x0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
</syntaxhighlight>
 
This version of the algorithm will return 0 if the input contains no positive elements (including when the input is empty).
Solution returns max negative value (-2147483648) when an empty set is provided.
 
The algorithm can be adapted to the case which disallows empty subarrays or to keep track of the starting and ending indices of the maximum subarray.