Created
December 9, 2020 17:27
-
-
Save SeanFelipe/843df09d32adbf4b1cd61e8aebea7561 to your computer and use it in GitHub Desktop.
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
=begin | |
I needed a few more minutes to run an optimization on the hacker rank exercise. | |
Problem: supply an array arr, such that: | |
- We sum each element in the array in sequence | |
- During the operation, the current total never drops below 1 | |
- What is the minimum starting value for a given array? | |
=end | |
def min_sum(arr) | |
idx = 0 | |
first_item = arr.first.to_i | |
current_min = 1 - first_item | |
total = first_item | |
valid = false | |
while ! valid | |
# reduce the size of the array to what's left to compute | |
current_arr = arr[idx..-1] | |
puts "current_arr length: #{current_arr.length}, current index: #{idx}" | |
current_arr.each_with_index do |ss, ii| | |
nn = ss.to_i | |
puts "current total: #{total} current_min: #{current_min}" | |
if total + nn >= 1 | |
total = total + nn | |
if ii == arr.length - 1 | |
# last item of array, success | |
valid = true | |
end | |
else | |
new_index = idx + ii | |
puts "stopped at index #{new_index}, total: #{total} nn: #{nn}" | |
idx = new_index | |
break | |
end | |
end | |
end | |
return current_min | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment