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
31 changes: 26 additions & 5 deletions lib/max_subarray.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@

# Time Complexity: ?
# Space Complexity: ?
# Time Complexity: O(n)
# Space Complexity: O(1)
def max_sub_array(nums)
return 0 if nums == nil
return 0 if nums == nil
return nil if nums.empty?

max = nums[0]
current_sum = 0

i = 0
while i < nums.length
current_sum += nums[i]

if current_sum > max
max = current_sum
end

if current_sum < 0
current_sum = 0
end

raise NotImplementedError, "Method not implemented yet!"
i += 1
end

return max
end


#pp max_sub_array([-2,1,-3,4,-1,2,1,-5,4])
25 changes: 20 additions & 5 deletions lib/newman_conway.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
# Time complexity: O(n)
# Space Complexity: O(n)
def newman_conway(num)
raise ArgumentError if num < 1
return "1" if num == 1

seq = [0, 1, 1]
i = 3
result = "1 1"

until i >= num + 1
current = seq[seq[i-1]] + seq[i - (seq[i-1])]
seq << current
result += " #{current}"
i += 1
end

return result
end


# Time complexity: ?
# Space Complexity: ?
def newman_conway(num)
raise NotImplementedError, "newman_conway isn't implemented"
end
#pp newman_conway(13)
52 changes: 26 additions & 26 deletions test/max_sub_array_test.rb
Original file line number Diff line number Diff line change
@@ -1,70 +1,70 @@
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]

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal 6
end

it "will work with a totally negative array" do
# Arrange
input = [-3, -4, -5, -6, -7]

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal(-3)
end

it "will work with a totally negative array with the largest element at the rear" do
# Arrange
input = [ -4, -5, -6, -7, -3]

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal(-3)
end

it "will work with a 1-element array" do
# Arrange
input = [3]

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal 3
end

it "will return nil for an empty array" do
# Arrange
input = []

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_be_nil
# Arrange
input = []
# Act
answer = max_sub_array(input)
# Assert
expect(answer).must_be_nil
end

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

# Act
answer = max_sub_array(input)

# Assert
expect(answer).must_equal 50
end

end
end