From 5eac499fc3c02bd7dd7f34cf6a88fa8455d4ba3a Mon Sep 17 00:00:00 2001 From: "Angela.oh" Date: Sun, 6 Oct 2019 12:21:17 -0700 Subject: [PATCH] passing tests --- lib/max_subarray.rb | 35 +++++++++++++++++++++++++++++++---- lib/newman_conway.rb | 25 ++++++++++++++++++++++--- test/max_sub_array_test.rb | 2 +- 3 files changed, 54 insertions(+), 8 deletions(-) diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..fabf5bf 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,35 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n^2) where n is size of nums +# Space Complexity: O(n) def max_sub_array(nums) return 0 if nums == nil - - raise NotImplementedError, "Method not implemented yet!" + return nil if nums.length == 0 + + size = nums.length + max_so_far = find_min(nums) + + i = 0 + while i < size + max_ending_here = 0 + j = i + while j < size + max_ending_here = max_ending_here + nums[j] + if max_so_far < max_ending_here + max_so_far = max_ending_here + end + j += 1 + end + i += 1 + end + return max_so_far +end + +def find_min(nums) + min = 0 + nums.each do |num| + if num < min + min = num + end + end + return min end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..24805c5 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,26 @@ -# Time complexity: ? -# Space Complexity: ? +# Time complexity: O(n) +# Space Complexity: O(n) def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + raise ArgumentError, "n must be >= 0" if num == 0 + + if num == 1 + return "1" + end + + output_string = "1 1" + i = 3 + while i > 2 && i <= num + new_num = newman_conway_helper(i) + output_string += " " + new_num.to_s + i += 1 + end + + return output_string +end + +def newman_conway_helper(num) + return 1 if num == 1 || num == 2 + return newman_conway_helper( newman_conway_helper(num - 1)) + newman_conway_helper(num - newman_conway_helper(num - 1)) end \ No newline at end of file diff --git a/test/max_sub_array_test.rb b/test/max_sub_array_test.rb index 3253cdf..e27e1ca 100644 --- a/test/max_sub_array_test.rb +++ b/test/max_sub_array_test.rb @@ -1,6 +1,6 @@ require_relative "test_helper" -xdescribe "max subarray" do +describe "max subarray" do it "will work for [-2,1,-3,4,-1,2,1,-5,4]" do # Arrange input = [-2,1,-3,4,-1,2,1,-5,4]