Last active
August 29, 2015 14:22
-
-
Save mcdavis/ad33af88948525820ecc 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
def max_slice(numbers) | |
best_sum = nil | |
best_slice = nil | |
numbers.each_with_index do |number, index| | |
numbers[index..numbers.size].each_with_index do |inner_number, inner_index| | |
sum_nums = numbers[index..inner_index+1] | |
unless sum_nums.empty? | |
sum = sum_nums.inject(0) { |sum, x| sum += x } | |
if best_sum.nil? || sum > best_sum | |
best_sum = sum | |
best_slice = sum_nums | |
end | |
end | |
end | |
end | |
p "for #{numbers} the best slice is #{best_slice}" | |
end | |
max_slice([-1, 5, 4]) # => [5, 4] | |
max_slice([-4]) # => [-4] | |
max_slice([-5, -4, -7]) # => [-4] | |
max_slice([1]) # => [1] | |
max_slice([-5, 4, 5, -1, 10, -5]) # => [4, 5, -1, 10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given an array, find the slice of the array that results in the highest sum. This can be the entire array or just a slice/segment from it.