diff --git a/lib/max_subarray.py b/lib/max_subarray.py index 4e892e0..3cd1a65 100644 --- a/lib/max_subarray.py +++ b/lib/max_subarray.py @@ -2,11 +2,22 @@ def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. - Time Complexity: ? - Space Complexity: ? + Time Complexity: O(n) + Space Complexity: O(1) """ - if nums == None: + if not nums: return 0 - if len(nums) == 0: - return 0 - pass + + if max(nums) < 0: + return max(nums) +# Kadane's Algorithm + max_so_far = 0 + max_ending_here = 0 + + for i in range(len(nums)): + max_ending_here = max_ending_here + nums[i] + if(max_ending_here < 0): + max_ending_here = 0 + if(max_so_far < max_ending_here): + max_so_far = max_ending_here + return max_so_far diff --git a/lib/newman_conway.py b/lib/newman_conway.py index 70a3353..5373a01 100644 --- a/lib/newman_conway.py +++ b/lib/newman_conway.py @@ -4,7 +4,18 @@ # Space Complexity: ? def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. - Time Complexity: ? - Space Complexity: ? + Time Complexity: O(n) single for loop to find nth element of sequence - linear + Space Complexity: O(n) use list to store cache which is required to compute nth element - linear """ - pass + if num == 0: + raise ValueError("Number cannot be zero") + elif num == 1: + return "1" + + cache = [0,1,1] + + for i in range(3, num + 1): + cache.append(cache[cache[i-1]] + cache[i - cache[i-1]]) + string = ' '.join([str(item) for item in cache[1:]]) + + return string