Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where I am doing wrong in calculation in maximum total of subarray?

Hi I am trying to find the maximum total from the list. I don’t understand where I am going wrong.

subarr = [8,-2,-4,-1] 

def sub(subarr):
    sum = 0
    m = max(subarr)
    for i in range(len(subarr)-1):
        for j in range(subarr[i+1],len(subarr)):
            sum = subarr[i] + subarr[j]
            if sum > m:
                m = sum
    return print(m)
sub(subarr)

Output:

16

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

8

>Solution :

Is this what you mean?

subarr = [8,-2,-4,-1] 

def sub(subarr):
    sum = 0
    m = max(subarr)
    for i in range(len(subarr)-1):
        sum = subarr[i]
        for j in range(i + 1,len(subarr)):
            sum += subarr[j]
            if sum > m:
                m = sum
    return print(m)
sub(subarr)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading