|
| 1 | +""" |
| 2 | +Kadane's algorithm to get maximum subarray sum |
| 3 | +https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d |
| 4 | +https://en.wikipedia.org/wiki/Maximum_subarray_problem |
| 5 | +""" |
| 6 | +test_data = ([-2, -8, -9], [2, 8, 9], [-1, 0, 1], [0, 0], []) |
| 7 | + |
| 8 | + |
| 9 | +def negative_exist(arr: list) -> int: |
| 10 | + """ |
| 11 | + >>> negative_exist([-2,-8,-9]) |
| 12 | + -2 |
| 13 | + >>> [negative_exist(arr) for arr in test_data] |
| 14 | + [-2, 0, 0, 0, 0] |
| 15 | + """ |
| 16 | + arr = arr or [0] |
| 17 | + max = arr[0] |
| 18 | + for i in arr: |
| 19 | + if i >= 0: |
| 20 | + return 0 |
| 21 | + elif max <= i: |
| 22 | + max = i |
| 23 | + return max |
| 24 | + |
| 25 | + |
| 26 | +def kadanes(arr: list) -> int: |
| 27 | + """ |
| 28 | + If negative_exist() returns 0 than this function will execute |
| 29 | + else it will return the value return by negative_exist function |
| 30 | +
|
| 31 | + For example: arr = [2, 3, -9, 8, -2] |
| 32 | + Initially we set value of max_sum to 0 and max_till_element to 0 than when |
| 33 | + max_sum is less than max_till particular element it will assign that value to |
| 34 | + max_sum and when value of max_till_sum is less than 0 it will assign 0 to i |
| 35 | + and after that whole process, return the max_sum |
| 36 | + So the output for above arr is 8 |
| 37 | +
|
| 38 | + >>> kadanes([2, 3, -9, 8, -2]) |
| 39 | + 8 |
| 40 | + >>> [kadanes(arr) for arr in test_data] |
| 41 | + [-2, 19, 1, 0, 0] |
| 42 | + """ |
| 43 | + max_sum = negative_exist(arr) |
| 44 | + if max_sum < 0: |
| 45 | + return max_sum |
| 46 | + |
| 47 | + max_sum = 0 |
| 48 | + max_till_element = 0 |
| 49 | + |
| 50 | + for i in arr: |
| 51 | + max_till_element += i |
| 52 | + if max_sum <= max_till_element: |
| 53 | + max_sum = max_till_element |
| 54 | + if max_till_element < 0: |
| 55 | + max_till_element = 0 |
| 56 | + return max_sum |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + try: |
| 61 | + print("Enter integer values sepatated by spaces") |
| 62 | + arr = [int(x) for x in input().split()] |
| 63 | + print(f"Maximum subarray sum of {arr} is {kadanes(arr)}") |
| 64 | + except ValueError: |
| 65 | + print("Please enter integer values.") |
0 commit comments