Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions lib/max_subarray.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@

# Time Complexity: ?
# Space Complexity: ?
# Time Complexity: O(n) where n = nums
# Space Complexity: O(1) only storing integers
def max_sub_array(nums)
Comment on lines +2 to 4

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

return 0 if nums == nil
return nil if nums.empty?

raise NotImplementedError, "Method not implemented yet!"
max_so_far = nums[0]
max_ending_here = 0

nums.each do |num|

if max_ending_here < 0
max_ending_here = num
else
max_ending_here += num
end

if max_ending_here > max_so_far
max_so_far = max_ending_here
end

end
return max_so_far
end
17 changes: 14 additions & 3 deletions lib/newman_conway.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@


# Time complexity: ?
# Space Complexity: ?
# Time complexity: O(n) where n is num
# Space Complexity: O(n) function stack call & array of (n) values
def newman_conway(num)
Comment on lines +3 to 5

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Nice work

raise NotImplementedError, "newman_conway isn't implemented"
return newman_helper(num, 3, [0, 1, 1]).slice(1, num).join(" ")
end

def newman_helper(num, current, memo)
raise ArgumentError if num == 0
if current > 2 && current <= num
current_idx = current
memo[current_idx] = memo[memo[current_idx - 1]] + memo[current_idx - memo[current_idx - 1]]
newman_helper(num, current + 1, memo)
end

return memo
end
24 changes: 23 additions & 1 deletion test/max_sub_array_test.rb
Original file line number Diff line number Diff line change
@@ -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]
Expand Down Expand Up @@ -67,4 +67,26 @@
expect(answer).must_equal 50
end

it "will work for [-2,1]" do
# Arrange
input = [-2,1]

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal 1
end

it "will work for [-3,-2,0,-1]" do
# Arrange
input = [-3,-2,0,-1]

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal 0
end

end