diff --git a/lib/max_subarray.py b/lib/max_subarray.py index 4e892e0..59d8e98 100644 --- a/lib/max_subarray.py +++ b/lib/max_subarray.py @@ -2,11 +2,20 @@ 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: return 0 if len(nums) == 0: return 0 - pass + # initialize maxSub -> first nsumber in the array + maxSub = nums[0] + currentSum = nums[0] + for index in range(1, len(nums)): + # start at index 1 + # compare current value with current sum + currentSum = max(nums[index], currentSum + nums[index]) + # assign to the max of itself compared to the currentSum + maxSub = max(maxSub, currentSum) + return maxSub diff --git a/lib/newman_conway.py b/lib/newman_conway.py index 70a3353..6a7ee2e 100644 --- a/lib/newman_conway.py +++ b/lib/newman_conway.py @@ -1,10 +1,40 @@ - -# Time complexity: ? -# 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) + Space Complexity: O(n) - it adds elements to result variable while (i <= num) """ - pass + # P(1) = 1 + # P(2) = 1 + # for all n > 2 + # P(n) = P(P(n - 1)) + P(n - P(n - 1)) + # use memoization table to store values for each calcula item + if num == 0: + raise ValueError() + if num == 1: + return "1" + if num == 2: + return "1 1" + record = [0] * (num + 1) + record[0] = 0 + record[1] = 1 + result = [] + if num > 2: + record[2] = 1 + + i = 3 + # first 3 items + while i<=num: + record[i] + # P(n) = P(P(n - 1)) + P(n - P(n - 1)) + record[i] = record[record[i-1]] + record[i- record[i-1]] + i +=1 + + i = 1 + result = [] + while (i <= num) : + # Display the sequence element + result.append(record[i]) + i += 1 + resultOutput = [str(item) for item in result] + return " ".join(resultOutput)