Created
November 30, 2017 23:01
-
-
Save Pierian-Data/51202d7a84e36537df97a7c9ca78061f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Yeah right, Noted!
…On Sun, 4 Sep, 2022, 7:00 am Linya Liu, ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
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
—
Reply to this email directly, view it on GitHub
<https://gist.github.com/51202d7a84e36537df97a7c9ca78061f#gistcomment-4289351>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AQ4KRJYND5RE5H3HRJUUVFDV4P3S3ANCNFSM4YYXS5HQ>
.
You are receiving this because you commented.Message ID:
***@***.***>
@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
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])