Skip to content

Commit d07d0d3

Browse files
committed
implement max_sub_array
1 parent 1da178b commit d07d0d3

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

lib/max_subarray.rb

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11

2-
# Time Complexity: ?
3-
# Space Complexity: ?
2+
# Time Complexity: O(n)
3+
# Space Complexity: O(1)
44
def max_sub_array(nums)
5-
return 0 if nums == nil
6-
7-
raise NotImplementedError, "Method not implemented yet!"
5+
return nil if nums.empty?
6+
7+
max_so_far = nums[0]
8+
max_ending_here = nums[0]
9+
10+
nums.each_with_index do |number, index|
11+
if index > 0
12+
max_ending_here = [number, max_ending_here + number].max
13+
max_so_far = [max_so_far, max_ending_here].max
14+
end
15+
end
16+
17+
return max_so_far
818
end

test/max_sub_array_test.rb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
require_relative "test_helper"
22

3-
xdescribe "max subarray" do
3+
describe "max subarray" do
44
it "will work for [-2,1,-3,4,-1,2,1,-5,4]" do
55
# Arrange
66
input = [-2,1,-3,4,-1,2,1,-5,4]
@@ -46,14 +46,14 @@
4646
end
4747

4848
it "will return nil for an empty array" do
49-
# Arrange
50-
input = []
49+
# Arrange
50+
input = []
5151

52-
# Act
53-
answer = max_sub_array(input)
52+
# Act
53+
answer = max_sub_array(input)
5454

55-
# Assert
56-
expect(answer).must_be_nil
55+
# Assert
56+
expect(answer).must_be_nil
5757
end
5858

5959
it "will work for [50, -50, 50]" do

0 commit comments

Comments
 (0)