FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
scripts/max_subarray_sum.py at main · epythonlab/scripts · GitHub
epythonlab
/
scripts
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
scripts
/
max_subarray_sum.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
24 lines (18 loc) · 663 Bytes
Breadcrumbs
scripts
/
max_subarray_sum.py
Copy path
File metadata and controls
24 lines (18 loc) · 663 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Python challenge: Given an array of integers,
# find the maximum possible sum of a subarray,
# where the subarray must contain at least one element.
# - This is a classic algorithmic problem that
# can be solved with a dynamic programming approach.
def
max_subarray_sum
(
nums
):
if
not
nums
:
return
0
# empty array
max_sum
=
nums
[
0
]
current_sum
=
nums
[
0
]
for
num
in
nums
[
1
:]:
current_sum
=
max
(
num
,
current_sum
+
num
)
max_sum
=
max
(
max_sum
,
current_sum
)
return
max_sum
# test this function
nums
=
[
-
2
,
1
,
-
3
,
4
,
-
1
,
2
,
1
,
-
5
,
4
]
result
=
max_subarray_sum
(
nums
)
print
(
f'max subarray sum is:
{
result
}
'
)
Back
|
FazBrowse Home
|
New Git URL