Created
January 8, 2015 18:36
-
-
Save compwron/fea94a0eac08695e30ca to your computer and use it in GitHub Desktop.
max_slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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