Skip to content

Instantly share code, notes, and snippets.

@mcdavis
Last active August 29, 2015 14:22
Show Gist options
  • Save mcdavis/ad33af88948525820ecc to your computer and use it in GitHub Desktop.
Save mcdavis/ad33af88948525820ecc to your computer and use it in GitHub Desktop.
Max Slice
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]
@mcdavis
Copy link
Author

mcdavis commented May 27, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment