Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding the doctests And Fixing the code in longest_sub_array #10151

Closed
wants to merge 8 commits into from
67 changes: 49 additions & 18 deletions dynamic_programming/longest_sub_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,55 @@
"""


class SubArray:
def __init__(self, arr):
# we need a list not a string, so do something to change the type
self.array = arr.split(",")

def solve_sub_array(self):
rear = [int(self.array[0])] * len(self.array)
sum_value = [int(self.array[0])] * len(self.array)
for i in range(1, len(self.array)):
sum_value[i] = max(
int(self.array[i]) + sum_value[i - 1], int(self.array[i])
)
rear[i] = max(sum_value[i], rear[i - 1])
return rear[len(self.array) - 1]
def longest_sub_array(arr: list):
"""
Find the longest continuous subarray with the maximum sum.

Args:
arr (list): A list of integers.

Returns:
A Integer which is the max subarray sum in the whole array.

Examples:
>>> longest_sub_array([1, 2, 3, 2, 5])
13

>>> longest_sub_array([5, -4, 3, -2, 1])
5

>>> longest_sub_array([1, 2, 3, -2, 5])
9

>>> longest_sub_array([10, 20, -30, 40, 50])
90

>>> longest_sub_array([])
0
"""

max_so_far = arr[0]
max_ending_here = arr[0]
max_len = 1
curr_len = 1

for i in range(1, len(arr)):
if max_ending_here < 0:
max_ending_here = arr[i]
curr_len = 1
else:
max_ending_here += arr[i]
curr_len += 1
if max_ending_here > max_so_far:
max_so_far = max_ending_here
max_len = curr_len
elif max_ending_here == max_so_far:
max_len = max(max_len, curr_len)

return max_len


if __name__ == "__main__":
whole_array = input("please input some numbers:")
array = SubArray(whole_array)
re = array.solve_sub_array()
print(("the results is:", re))
import doctest

doctest.testmod()
Loading