GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Changed max_subarray_sum · code3002/coding-problems@be37804

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Dynamic Programming
    • max_subarray_sum.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Lists/max_subarray_sum.py‎ ‎Dynamic Programming/max_subarray_sum.py‎Lists/max_subarray_sum.py renamed to Dynamic Programming/max_subarray_sum.py

Copy file name to clipboardExpand all lines: Dynamic Programming/max_subarray_sum.py
+7-15Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'''
22
Maximum subarray sum
33
4-
The subarray must be contiguous
4+
The subarray must be contiguous.
55
66
Sample input: [-2, -3, 4, -1, -2, 1, 5, -3]
77
Sample output: 7
@@ -21,29 +21,21 @@
2121
############
2222

2323
def max_subarray_sum(a):
24-
# max_sum, max_start_idx, max_end_idx
25-
max_sum = (0, 0, 0)
26-
2724
i = 0
2825
n = len(a)
2926
curr_sum = 0
30-
start_idx = 0
27+
max_sum = 0
3128

3229
while i < n:
33-
curr_sum += a[i]
30+
# restart the current sum if 0 or smaller, we care only about the positive sums
31+
curr_sum = max(0, curr_sum + a[i])
3432

35-
if curr_sum <= 0:
36-
# restart the current sum, we care only about positive sums
37-
start_idx = i + 1
38-
curr_sum = 0
39-
else:
40-
# check if this is the max sum
41-
if curr_sum > max_sum[0]:
42-
max_sum = (curr_sum, start_idx, i + 1)
33+
# check if this is the max sum
34+
max_sum = max(max_sum, curr_sum)
4335

4436
i += 1
4537

46-
return max_sum[0]
38+
return max_sum
4739

4840

4941
###########

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.