GeezerVison is showing github.com — more pythonic iteration; positive -> non-negative in the description;… · spudmonkey/coding-problems@906b91d
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: Dynamic Programming/max_subarray_sum.py +10-9Lines changed: 10 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 9 | 9 |
| 10 | 10 | ========================================= | 11 | 11 | Need only one iteration, in each step add the current element to the current sum. | 12 | | -When the sum is equal or less than 0, reset the sum to 0 and continue with adding. (we care only about the positive sums) | | 12 | +When the sum is less than 0, reset the sum to 0 and continue with adding. (we care only about non-negative sums) | 13 | 13 | After each addition, check if the current sum is greater than the max sum. (Called Kadane's algorithm) | 14 | 14 | Time Complexity: O(N) | 15 | 15 | Space Complexity: O(1) | | 21 | 21 | ############ | 22 | 22 |
| 23 | 23 | def max_subarray_sum(a): | 24 | | - i = 0 | 25 | | - n = len(a) | 26 | 24 | curr_sum = 0 | 27 | 25 | max_sum = 0 | 28 | 26 |
| 29 | | - while i < n: | 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]) | | 27 | + for val in a: | | 28 | + # extend the current sum with the curren value; | | 29 | + # reset it to 0 if it is smaller than 0, we care only about non-negative sums | | 30 | + curr_sum = max(0, curr_sum + val) | 32 | 31 |
| 33 | 32 | # check if this is the max sum | 34 | 33 | max_sum = max(max_sum, curr_sum) | 35 | 34 |
| 36 | | - i += 1 | 37 | | - | 38 | 35 | return max_sum | 39 | 36 |
| 40 | 37 |
| @@ -52,4 +49,8 @@ def max_subarray_sum(a): | 52 | 49 |
| 53 | 50 | # Test 3 | 54 | 51 | # Correct result => 7 | 55 | | -print(max_subarray_sum([-2, -5, 6, -2, -3, 1, 5, -6])) | | 52 | +print(max_subarray_sum([-2, -5, 6, -2, -3, 1, 5, -6])) | | 53 | + | | 54 | +# Test 4 | | 55 | +# Correct result => 0 | | 56 | +print(max_subarray_sum([-6, -1])) |
|