this may be an alternative approach of doing it:
def consequtive_sub_lists(l):
sublists = []
for iter, item in enumerate(l):
sublists.append([item])
cur_sublist = [item]
for idx in range(iter+1, len(l)):
cur_sublist.append(l[idx])
sublists.append(cur_sublist.copy())
return sublists
sublists = consequtive_sub_lists([1,2,-3,4])
max_sum, max_list = max([(sum(item), item) for item in sublists])
print(f"max_sum: {max_sum}")
print(f"max_list: {max_list}")
output:
max_sum: 4
max_list: [4]
Some Explanations:
I sepparated the solution into 2 main steps:
- create all consequtive sub_lists out of given list (as list of lists)
- out of it, find out the element that has the maximum sum over it's elements
For the Kadane's algorithm (to make it similar to the solution in here)
def max_sequence(arr):
max = 0
sum = 0
for i in arr:
sum += i
if sum > max:
max = sum
if sum < 0:
sum = 0
return max
this one is work
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…