From 490c5bafd517b671b65844395e04ed760a91dda1 Mon Sep 17 00:00:00 2001 From: Shubha Rajan Date: Sat, 12 Oct 2019 17:42:18 -0700 Subject: [PATCH 1/2] solved newman conway exercise --- lib/newman_conway.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..bdc3951 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -3,5 +3,11 @@ # Time complexity: ? # Space Complexity: ? def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + seq = [0, 1, 1] + raise ArgumentError if num <= 0 + return seq[1..num].join(' ')if num == 1 || num == 2 + (3..num).each do |i| + seq[i] = seq[seq[i-1]] + seq[i - seq[i - 1]] + end + return seq[1..num].join(' ') end \ No newline at end of file From 1a2ec789e5623fb29398d610e0984f0547186c0c Mon Sep 17 00:00:00 2001 From: Shubha Rajan Date: Sat, 12 Oct 2019 19:25:02 -0700 Subject: [PATCH 2/2] passing tests for max subarray --- lib/max_subarray.rb | 20 +++++++++++++++----- lib/newman_conway.rb | 4 ++-- test/max_sub_array_test.rb | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..9b0b8ce 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,18 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) +# Space Complexity: O(1) def max_sub_array(nums) - return 0 if nums == nil - - raise NotImplementedError, "Method not implemented yet!" + return nil if nums == nil || nums.empty? + max = nums[0] + curr_max = nums[0] + (1...nums.length).each do |i| + curr_max = curr_max + nums[i] + if nums[i] > curr_max + max = nums[i] if nums[i] > max + curr_max = nums[i] + else + max = curr_max if curr_max > max + end + end + return max end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index bdc3951..8eacf20 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,7 @@ -# Time complexity: ? -# Space Complexity: ? +# Time complexity: O(n) +# Space Complexity: O(n) def newman_conway(num) seq = [0, 1, 1] raise ArgumentError if num <= 0 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]