Tuesday, April 20, 2021

Python: Finding largest continuous sum in a list/array

 Problem Statement:

Given a list of integers (both positive and negative) find the largest continuous sum.

e.g. 

Input:

list1 = [1, 2, -1, 3, 4, 10, 10, -10, -1]

Output: 29

Solution:

def largest_cont_sum(list1):
    max_sum = current_sum = 0
    
    if len(list1) == 0:
        return "There is no any element in the List"
    
    for num in list1:
        current_sum = max(current_sum + num, num)
        max_sum = max(current_sum, max_sum)
    
    return max_sum
list1 = [1,2,-1,3,4,10,10,-10,-1]
print("The Largest continuous sum is:",largest_cont_sum(list1))

Output: The Largest continuous sum is: 29

No comments:

Post a Comment

Some useful parameters

Dielectric constant  Metals have infinite Dielectric constant  As usually metals permittivity is very large than of free space hence its Die...