Skip to content

Instantly share code, notes, and snippets.

@compwron
Created January 8, 2015 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save compwron/fea94a0eac08695e30ca to your computer and use it in GitHub Desktop.
Save compwron/fea94a0eac08695e30ca to your computer and use it in GitHub Desktop.
max_slice
# You are asked to write a max_slice function which takes as an input an array of integers, and returns the slice with the largest sum of the elements
a = [1, 2, 3, 4, 5]
b = [1, -2, 6, -4, 5]
[1]
[1, -2]
[1, -2, 6]
[-2, 6]
c = [1, -2]
def max_slice arr
return [] if arr.empty?
largest_slice = [arr[0]]
largest = arr[0]
current = arr.min
(0..arr.size-1).each {|i|
(i..arr.size-1).each { |j|
current = arr[i..j].inject(:+)
if current > largest
largest_slice = arr[i..j]
largest = current
end
}
}
largest_slice
end
def should answer, real
puts "#{real} should be #{answer}" unless real == answer
end
should([6, -4, 5] , max_slice(b))
should([] , max_slice([]))
should([1] , max_slice([1]))
should([1, 2] , max_slice([1, 2]))
should([-1] , max_slice([-3, -1, -2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment