From 902f983c42de5331c9970a063389cbd0ceef28b3 Mon Sep 17 00:00:00 2001 From: Mariya Burrows Date: Mon, 30 Mar 2020 20:48:07 -0700 Subject: [PATCH] completed hw --- lib/max_subarray.rb | 25 +++++++++++++++++++++---- lib/newman_conway.rb | 32 +++++++++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..98577ce 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,25 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) +# Space Complexity: O(1) def max_sub_array(nums) - return 0 if nums == nil + return 0 if nums == nil || nums.empty? - raise NotImplementedError, "Method not implemented yet!" + max = nums[0] + current = nums[0] + + nums.each do |index| + temp = current + max[index] + + if temp > nums[index] + current = max + else + current = nums[index] + end + + if max < current + max = current + end + end + + return max end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..617935d 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,33 @@ -# Time complexity: ? -# Space Complexity: ? +# Time complexity: O(1) +# Space Complexity: O(n) + +def newman_helper(num, newman_hash) + if newman_hash[num] + return newman_hash[num] + end + + if num == 1 || num == 2 + return 1 + else + newman_hash[num] = newman_helper(newman_helper(num - 1, newman_hash), newman_hash) + + newman_helper(num - newman_helper(num - 1, newman_hash), newman_hash) + return newman_hash[num] + end +end + def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + newman_hash = {} + + if num < 1 + raise ArgumentError + end + newman_array = [] + + num.times do |i| + newman_array << newman_helper(i + 1, newman_hash) + end + + return newman_array.join(" ") end \ No newline at end of file