Skip to content

Instantly share code, notes, and snippets.

@Pierian-Data
Created November 30, 2017 23:01
Show Gist options
  • Save Pierian-Data/51202d7a84e36537df97a7c9ca78061f to your computer and use it in GitHub Desktop.
Save Pierian-Data/51202d7a84e36537df97a7c9ca78061f to your computer and use it in GitHub Desktop.
def large_cont_sum(arr):
# Check to see if array is length 0
if len(arr)==0:
return 0
# Start the max and current sum at the first element
max_sum=current_sum=arr[0]
# For every element in array
for num in arr[1:]:
# Set current sum as the higher of the two
current_sum=max(current_sum+num, num)
# Set max as the higher between the currentSum and the current max
max_sum=max(current_sum, max_sum)
return max_sum
@Sreeja123ut
Copy link

The simple below code is enough to sort this question right?

def sumofmax(n):
v = 0
for i in n[1:]:
v = v + i
return v
sumofmax([1,2,3,-4,9])

@Liulinya
Copy link

Liulinya commented Sep 4, 2022

The simple below code is enough to sort this question right?

def sumofmax(n): v = 0 for i in n[1:]: v = v + i return v sumofmax([1,2,3,-4,9])

Great simplified code Sreeja! Just one thing, the third line shall be "for i in n[0:]:" since the array list started from position 0

@Sreeja123ut
Copy link

Sreeja123ut commented Sep 4, 2022 via email

@dgerok
Copy link

dgerok commented Jun 12, 2023

@Sreeja123ut , @Liulinya
Nope.
Try other examples:

def largest_cont_sum(arr):
    if len(arr) == 0:
        return 0
    else:
        curr_sum = max_sum = arr[0]
        for n in arr[1:]:
            curr_sum = max(curr_sum + n, n)
            max_sum  = max(curr_sum, max_sum)
        return max_sum

a0 = []
a1 = [7,8,9]
a2 = [-1,7,8,9,-10]
a3 = [2,3,-10,9,2]
a4 = [2,11,-10,9,2]
a5 = [12,-10,7,-8,4,6]
a6 = [1,2,-5,7,-1,9,3,-15,4,11]
a7 = [-4,-7,-1,-6]
aa = [a0,a1,a2,a3,a4,a5,a6,a7]
for a in aa:
    print(a, "\n", largest_cont_sum(a))

The result should look like:

[] 
 0
[7, 8, 9] 
 24
[-1, 7, 8, 9, -10] 
 24
[2, 3, -10, 9, 2] 
 11
[2, 11, -10, 9, 2] 
 14
[12, -10, 7, -8, 4, 6] 
 12
[1, 2, -5, 7, -1, 9, 3, -15, 4, 11] 
 18
[-4, -7, -1, -6] 
 -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment