For context, this is the problem statement in Codewars: Problem Statement
It's essentially the classic 'Find the maximum subarray sum' problem, though with the important added detail of the fact that a '0' should be returned given an array of all negative numbers, instead of just the largest negative number value.
To begin with, I'm fully aware that this solution is not a terribly good or efficient one. That being said, the logic to me still makes sense so I don't quite understand why it works for certain inputs and not others. I can't provide the inputs for which this program is invalid due to the fact that the test cases are hidden in Codewars.
I've tried running the code using examples like;
- [1, 0, 2, -3, 6] (should return 6)
- [-2, 1, -3, 4, -1, 2, 1, -5, 4] (should return 6)
- [-2, -3, 4, -1, 5, 1, 5, -3] (should return 14)
- etc. And they've all worked fine
Again, I just wanna know the logic behind why this code is incorrect. I'm not looking for an alternative solution that is correct (I'm already aware of the existence of Kadane's algorithm now). This was my first blind attempt at solving this problem so I'd really like to know what I did wrong so that I can learn from it.
def max_sequence(arr):
max_sum = 0
max_subarr_index = 0
for i, val in enumerate(arr):
max_sum = max(max_sum, sum(arr[max_subarr_index:i+1]), val)
if max_sum == val:
max_subarr_index = i
return max_sum