diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..5a7a5ef 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,22 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: o(n) - one loop for each num in nums +# Space Complexity: o(1) - creates 2 variables only, no matter value of nums def max_sub_array(nums) - return 0 if nums == nil + return 0 if nums.nil? + return nil if nums.empty? - raise NotImplementedError, "Method not implemented yet!" -end + max_so_far = nums[0] + max_for_sub_array = 0 + + nums.each do |num| + max_for_sub_array = max_for_sub_array + num + if num > max_for_sub_array + max_for_sub_array = num + end + if max_for_sub_array > max_so_far + max_so_far = max_for_sub_array + end + end + return max_so_far + +end \ No newline at end of file diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..c0c4daf 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,20 @@ -# Time complexity: ? -# Space Complexity: ? +# Time complexity: o(n) - runtime for most values of num and in worst case is n - 2 calculations +# Space Complexity: o(n) - size of sequence and answer string has linear dependency on value of num def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + raise ArgumentError if num == 0 + return "1" if num == 1 + return "1 1" if num == 2 + + sequence = [0, 1, 1] + + answer = "1 1" + + (3..num).each do |n| + p_last = sequence[n - 1] + sequence << (sequence[p_last] + sequence[n - p_last]) + answer += " #{sequence[n]}" + end + return answer 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]