diff --git a/lib/max_subarray.rb b/lib/max_subarray.rb index 5204edb..c694158 100644 --- a/lib/max_subarray.rb +++ b/lib/max_subarray.rb @@ -1,8 +1,38 @@ -# Time Complexity: ? -# Space Complexity: ? -def max_sub_array(nums) - return 0 if nums == nil +# Time Complexity: O(n) +## The method iterates over the entire array but does so only once + +# Space Complexity: O(1) +## There are a limited number of variables that are constantly being re-assessed, so as the input goes to infitity the space requirements do not grow. + +def max_sub_array(number_array) + length = number_array.length + if length == 0 + return nil + elsif length == 1 + return number_array[0] + end + + max_so_far = number_array[0] + max_ending_here = 0 + + i = 0 + + until i == length do + + max_ending_here = max_ending_here + number_array[i] + + if max_so_far < max_ending_here + max_so_far = max_ending_here + i += 1 + elsif max_ending_here < 0 + max_ending_here = 0 + i += 1 + else + i+= 1 + end + end + + return max_so_far - raise NotImplementedError, "Method not implemented yet!" end diff --git a/lib/newman_conway.rb b/lib/newman_conway.rb index 4c985cd..c5f4910 100644 --- a/lib/newman_conway.rb +++ b/lib/newman_conway.rb @@ -1,7 +1,43 @@ -# Time complexity: ? -# Space Complexity: ? +# Time complexity: O(n) +## As the number goes to infinity, its values have to be assessed relative to whatever's already in the array, but because it's based on an array, the look-up cost is very low given that an index value is being passed in. +# Space Complexity: O(n) +## As the number goes to infinity, the amount of space will grow at the same rate + def newman_conway(num) - raise NotImplementedError, "newman_conway isn't implemented" + + if num == 0 || num == nil + raise ArgumentError + elsif num == 1 + return "1" + elsif num == 2 + return "1 1" + end + + if num >= 3 + return_array = [1, 1] + end + + i = 3 + + until i > num do + + # P(n) = P(P(n - 1)) + P(n - P(n - 1)) + + temp_a = return_array[(return_array[i-2])-1] + + temp_b = return_array[(i-(return_array[i-2]))-1] + + temp = temp_a + temp_b + + i += 1 + + return_array.push temp + end + + return_string = return_array.join(" ") + + return return_string + end \ No newline at end of file