diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..0feb566 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,20 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) +# Space Complexity: O(1) def max_sub_array(nums) + # you calculated return 0 if nums == nil - raise NotImplementedError, "Method not implemented yet!" + current_max = nums[0] + global_max = nums[0] + + i = 1 + + while i < nums.length + current_max = [nums[i], (current_max + nums[i])].max + global_max = [global_max, current_max].max + i += 1 + end + + return global_max end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..9f19d5d 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,41 @@ -# Time complexity: ? -# Space Complexity: ? +# Time complexity: O(n) +# Space Complexity: O(1) def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" -end \ No newline at end of file + raise ArgumentError, "num must be >= 0" if num <= 0 + return "1" if num == 1 + return "1 1" if num == 2 + + # I made a new premade array that was the length plus one of num that was passed in + array = Array.new(num + 1){} + + # Build a memo of subproblems + + # value at index 1 and 2 are set two zero, but why is value at index 0 nil? How did everyone initialize + # their array? + array[1] = 1 + array[2] = 1 + + # initialize i to 3 because values at index 1 and 2 are already set. + i = 3 + + + while i < array.length + + # I used the sum of previous values in the array to get the next value. So I initialized i to index 3 since that is the next + # value that needs to be calculated. As a result of plugging 3 into that equation, I got 2. So the value at index 3 is 2. And you'd just keep + # doing that until you go past the length of the array. + if i > 2 + array[i] = array[array[i - 1]] + array[i - array[i - 1]] + end + + i += 1 + end + + # used shift to pop off first value which was nil + array.shift() + + # joined them so answer would come out as string instead of array to pass the test + return array.join(" ") +end 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]