max subarray code example
Example 1: max subsequence sum in array
def max_subarray(numbers):
"""Find the largest sum of any contiguous subarray."""
best_sum = 0 # or: float('-inf')
current_sum = 0
for x in numbers:
current_sum = max(0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
Example 2: kadane algorithm actual
//Kadene's algorithm where empty array is allowed.
int ms,cs;
ms=cs=0;
for(int i=0;i<n;i++)
{
cs=cs+a[i];
if(cs<0)
{
cs=0;
}
ms=max(ms,cs);
}
cout<<ms<<endl;
}