Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to get maximum product of sublist in Python

1 Answer

0 votes
def getMaxProductOfSubarray(lst):
    lenn = len(lst)
    
    if not lenn:
        return 0
 
    max_current_index = min_current_index = max_product = lst[0]

    print("lst[0] =", lst[0], "max_current_index =", max_current_index, " min_current_index =", min_current_index, " max_product=", max_product)
    
    for i in range(1, lenn):
        temp = max_current_index
 
        max_current_index = max(lst[i], max(lst[i] * max_current_index, lst[i] * min_current_index))
 
        min_current_index = min(lst[i], min(lst[i] * temp, lst[i] * min_current_index))
        
        print("lst[i] =", lst[i], "max_current_index =", max_current_index, " min_current_index =", min_current_index, " max_product=", max_product)
 
        max_product = max(max_product, max_current_index)
        
        print("max_product =", max_product)
 
    return max_product
 
 
lst = [-4, 8, -2, 5, 0, -7, 9, -3, 6]

print("maximum product =", getMaxProductOfSubarray(lst))




'''
run:

lst[0] = -4 max_current_index = -4  min_current_index = -4  max_product= -4
lst[i] = 8 max_current_index = 8  min_current_index = -32  max_product= -4
max_product = 8
lst[i] = -2 max_current_index = 64  min_current_index = -16  max_product= 8
max_product = 64
lst[i] = 5 max_current_index = 320  min_current_index = -80  max_product= 64
max_product = 320
lst[i] = 0 max_current_index = 0  min_current_index = 0  max_product= 320
max_product = 320
lst[i] = -7 max_current_index = 0  min_current_index = -7  max_product= 320
max_product = 320
lst[i] = 9 max_current_index = 9  min_current_index = -63  max_product= 320
max_product = 320
lst[i] = -3 max_current_index = 189  min_current_index = -27  max_product= 320
max_product = 320
lst[i] = 6 max_current_index = 1134  min_current_index = -162  max_product= 320
max_product = 1134
maximum product = 1134

'''
 

 



answered Jul 10, 2022 by avibootz

Related questions

1 answer 140 views
1 answer 113 views
3 answers 275 views
1 answer 78 views
1 answer 83 views
...