From c6f2555e5e52276954285b82294f4d876d2ebc9a Mon Sep 17 00:00:00 2001 From: charlottea Date: Sun, 18 Oct 2020 19:48:46 -0700 Subject: [PATCH] implement methods and pass tests --- lib/max_subarray.rb | 20 ++++++++++++++++---- lib/newman_conway.rb | 17 +++++++++++++---- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..15ea5b9 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,20 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) +# Space Complexity: O(1) def max_sub_array(nums) - return 0 if nums == nil + return nil if nums.nil? || nums.empty? - raise NotImplementedError, "Method not implemented yet!" + max_so_far = nums[0] + max_ending_here = nums[0] + + i = 1 + while i < nums.length + max_ending_here += nums[i] + # assign max to current num if max_ending_here is less than nums[i] + max_ending_here = nums[i] if max_ending_here < nums[i] + max_so_far = max_ending_here if max_so_far < max_ending_here + i += 1 + end + + return max_so_far end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..eb4c36a 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,16 @@ +# Time complexity: o(n) +# Space Complexity: o(n) +def newman_conway(num) + raise ArgumentError if num <= 0 + return "1" if num == 1 + return "1 1" if num == 2 + array = [0, 1, 1] + i = 3 + while i <= num + array[i] = array[array[i - 1]] + array[i - array[i - 1]] + i += 1 + end -# Time complexity: ? -# Space Complexity: ? -def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + return array[1..-1].join(" ") end \ No newline at end of file