Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
=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