diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..33d074e 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,16 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) => because I iterate depending on the input (nums) +# Space Complexity: O(1) => because I use the constant numbers of the space (2 variables) def max_sub_array(nums) - return 0 if nums == nil + return nil if nums.nil? || nums.empty? - raise NotImplementedError, "Method not implemented yet!" + max_so_far = nums[0] + current_max = nums[0] + + nums[1..-1].each do |current_num| + current_max = [current_num, current_num + current_max].max + max_so_far = [current_max, max_so_far].max + end + + return max_so_far end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..4313a93 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,21 @@ -# Time complexity: ? -# Space Complexity: ? -def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" +# Time complexity: O(n) => because I iterate depending on the input (num) +# Space Complexity: O(n) => because I create a new array depending on the input (num) + +def newman_conway(num) # 9 + raise ArgumentError if num == 0 + solution = [] + + (1..num).each do |n| + if n == 1 || n == 2 + solution[n] = 1 + else + # P(P(n - 1)) + P(n - P(n - 1)) + solution[n] = solution[solution[n - 1]] + solution[n - solution[n - 1]] + end + + end + + return solution[1..-1].join(" ") 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..ac403f9 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] @@ -46,14 +46,14 @@ end it "will return nil for an empty array" do - # Arrange - input = [] + # Arrange + input = [] - # Act - answer = max_sub_array(input) + # Act + answer = max_sub_array(input) - # Assert - expect(answer).must_be_nil + # Assert + expect(answer).must_be_nil end it "will work for [50, -50, 50]" do