From 9037c24b2166a25b14138bb8af3306b933298b6e Mon Sep 17 00:00:00 2001 From: Janice Huang Date: Sat, 28 Mar 2020 11:55:12 -0700 Subject: [PATCH 1/3] get newman conway passing tests --- lib/newman_conway.rb | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..5778063 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,18 @@ -# 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, "Number must be greater than zero!" if num < 1 + return "1" if num == 1 + return "1 1" if num == 2 + array = [0, 1, 1] + index = 3 + until index == num + 1 + new_num = array[array[index - 1]] + array[index - (array[index - 1])] + array << new_num + index += 1 + end + array.shift + return array.join(" ") end \ No newline at end of file From ad589ad2794fcd6f7aeb7603f98a4c79261a5bd3 Mon Sep 17 00:00:00 2001 From: Janice Huang Date: Sat, 28 Mar 2020 20:54:53 -0700 Subject: [PATCH 2/3] get max sub array tests to pass --- lib/max_subarray.rb | 17 ++++++++++++++--- test/max_sub_array_test.rb | 2 +- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..bf9fba4 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -2,7 +2,18 @@ # Time Complexity: ? # Space Complexity: ? def max_sub_array(nums) - return 0 if nums == nil - - raise NotImplementedError, "Method not implemented yet!" + return 0 if nums == nil + return nil if nums == [] + return nums[0] if nums.length == 1 + local_max = 0 + global_max = -Float::INFINITY + index = 0 + while index < nums.length + local_max = [nums[index], local_max + nums[index]].max + if local_max > global_max + global_max = local_max + end + index += 1 + end + return global_max end 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] From 5795a213b20db6cab82ef0faefa702f24aee4821 Mon Sep 17 00:00:00 2001 From: Janice Huang Date: Sat, 28 Mar 2020 20:58:01 -0700 Subject: [PATCH 3/3] add time and space complexities --- lib/max_subarray.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index bf9fba4..c59db98 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,6 +1,6 @@ -# 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 == []