diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..e3d3baa 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,24 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) +# Space Complexity: O(1) def max_sub_array(nums) - return 0 if nums == nil + return nil if nums.nil? || nums.empty? + return nums[0] if nums.length == 1 + + highest_peak = nums[0] + highest = nums[0] + i = 1 + + while i < nums.length + highest_peak += nums[i] + + highest_peak = nums[i] if highest_peak < nums[i] + highest = highest_peak if highest < highest_peak + i += 1 + end + + return highest - raise NotImplementedError, "Method not implemented yet!" end + + diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..a71d2fe 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,26 @@ +# Time complexity: O(n) +# Space Complexity: O(n) - -# Time complexity: ? -# Space Complexity: ? def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" -end \ No newline at end of file + raise ArgumentError.new if num == 0 + + return "1" if num == 1 + return "1 1" if num == 2 + + array = [] + array[0] = 0 + array[1] = 1 + array[2] = 1 + tally = "1 1" + i = 3 + + until i > num + array[i] = array[array[i - 1]] + array[i - array[i - 1]] + tally += " #{array[i]}" + i += 1 + end + + return tally +end + +#research source: https://www.geeksforgeeks.org/print-n-terms-newman-conway-sequence/ 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]