Skip to content

Instantly share code, notes, and snippets.

@mrdougwright
Created September 22, 2015 18:34
Show Gist options
  • Save mrdougwright/62ce1d4f5469855cd5d9 to your computer and use it in GitHub Desktop.
Save mrdougwright/62ce1d4f5469855cd5d9 to your computer and use it in GitHub Desktop.
Max Slice
arr = [-10,-5,6,6,-10,-100]
arr2 = [10,-5,6,6,-10,-100]
def max_slice(arr)
max = 0
biggest_slice = arr[0..1]
arr.each_with_index do |x,i|
arr.each_with_index do |y,index|
if sum(arr[index..i]) > max
biggest_slice = arr[index..i]
max = sum(arr[index..i])
end
end
end
p biggest_slice
end
def sum(arr)
arr = Array(arr)
arr.inject(0) { |sum, x| sum + x.to_i }
end
max_slice(arr)
def assert_equal(func,value)
if func == value
puts "1 test passed."
else
puts "1 test failed."
puts "Expected #{value}. Got #{func}."
end
end
assert_equal(max_slice(arr),[6,6])
assert_equal(max_slice(arr2),[10,-5,6,6])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment