Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - Maximum Subarray sum - Where is my solution wrong? Kadane's Algorithm

Here is a description of the problem:

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

My solution so far is:

def max_sequence(arr):
sum = 0
max = 0
for i in arr:
    sum += i


    if i > max:
        max = i
        sum = max
        

    elif sum > max:
        max = sum
    
return(max)

It works on simple examples but not on random ones... Could you please help me where I made a mistake / what I didn't consider?

see the output from Codewars

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...