From 1da1ab0773e8cb74693dc53b29a0511f83c94098 Mon Sep 17 00:00:00 2001 From: John Law Date: Tue, 29 Oct 2019 00:44:57 +0800 Subject: [PATCH] Improve doctest and comment for maximum sub-array problem (#1503) * Doctest and comment for maximum sub-array problem More examples and description for max_sub_array.py * Update max_sub_array.py * Update max_sub_array.py * Fix doctest --- dynamic_programming/max_sub_array.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/dynamic_programming/max_sub_array.py b/dynamic_programming/max_sub_array.py index eb6ab41bf..f7c820971 100644 --- a/dynamic_programming/max_sub_array.py +++ b/dynamic_programming/max_sub_array.py @@ -2,9 +2,6 @@ author : Mayank Kumar Jha (mk9440) """ from typing import List -import time -import matplotlib.pyplot as plt -from random import randint def find_max_sub_array(A, low, high): @@ -43,15 +40,23 @@ def find_max_cross_sum(A, low, mid, high): def max_sub_array(nums: List[int]) -> int: """ - Finds the contiguous subarray (can be empty array) - which has the largest sum and return its sum. + Finds the contiguous subarray which has the largest sum and return its sum. - >>> max_sub_array([-2,1,-3,4,-1,2,1,-5,4]) + >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 + + An empty (sub)array has sum 0. >>> max_sub_array([]) 0 - >>> max_sub_array([-1,-2,-3]) + + If all elements are negative, the largest subarray would be the empty array, + having the sum 0. + >>> max_sub_array([-1, -2, -3]) 0 + >>> max_sub_array([5, -2, -3]) + 5 + >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) + 187 """ best = 0 current = 0 @@ -64,6 +69,12 @@ def max_sub_array(nums: List[int]) -> int: if __name__ == "__main__": + """ + A random simulation of this algorithm. + """ + import time + import matplotlib.pyplot as plt + from random import randint inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: