diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..d451574 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,39 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) where n is the length of the array +# Space Complexity: O(1) + def max_sub_array(nums) - return 0 if nums == nil + return nil if nums == [] + + max_so_far = nums[0] + sum_ending_here = nums[0] + + # ----------------------------------------------------- + # SOLUTION 1 + nums[1..-1].each do |num| + + sum_ending_here = [sum_ending_here + num, num].max + + if max_so_far < sum_ending_here + max_so_far = sum_ending_here + end + end + + # ----------------------------------------------------- + + # SOLUTION 2 + + # nums[1..-1].each do |num| + + # sum_ending_here = sum_ending_here + num + + # if max_so_far < sum_ending_here + # max_so_far = sum_ending_here + # elsif sum_ending_here < 0 + # sum_ending_here = 0 + # end + # end + # ----------------------------------------------------- - raise NotImplementedError, "Method not implemented yet!" + return max_so_far end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..4d7a47b 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,27 @@ +# Time complexity: O(n) +# Space Complexity: O(n) - -# Time complexity: ? -# Space Complexity: ? def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + solution = [1] + raise ArgumentError, "Number must be 1 or greater" if num <1 + p(num, solution) + + string_solution = "" + solution.each do |char| + string_solution << "#{char.to_s} " + end + + return string_solution[0...-1] +end + +def p(n, s) + return s[n-1] if s[n-1] + + if (n == 2) && !s[2-1] + s[2-1] = 1 + else + s[n-1] = p(p(n - 1, s), s) + p(n - p(n - 1, s), s) + end + + return s[n-1] 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..37635f0 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] @@ -67,4 +67,28 @@ expect(answer).must_equal 50 end + it "will work for [50, -51, 50]" do + # This test (which I added) is failing + + # Arrange + input = [50, -51, 50] + + # Act + answer = max_sub_array(input) + + # Assert + expect(answer).must_equal 50 + end + + it "will work for [-2,1,-3,4,-1,2,1,-5,4,12]" do + # Arrange + input = [4,-2,1,-3,4,-1,2,1,-5,4,12] + + # Act + answer = max_sub_array(input) + + # Assert + expect(answer).must_equal 17 + end + end \ No newline at end of file