Skip to content

Instantly share code, notes, and snippets.

@stamaniorec
Last active October 31, 2015 11:56
Show Gist options
  • Select an option

  • Save stamaniorec/f555c67483135902bdfe to your computer and use it in GitHub Desktop.

Select an option

Save stamaniorec/f555c67483135902bdfe to your computer and use it in GitHub Desktop.
#algo #ruby
# You are driving a car.
# You start moving with a velocity of V1 meters per second.
# Every second you can change your velocity with D meters per second.
# After T seconds, you want to be driving with a velocity of V2.
# What is the maximum distance you can travel during those T seconds?
# 5
# 6
# 4
# 2
# Expected output: 26
# Explanation: 5 + 7 + 8 + 6
# 14
# 14
# 11
# 0
# Expected output: 154
# Explanation: You cannot change your velocity, therefore 14 * 11 = 154
def solution(cur_speed, target_speed, delta, seconds)
if seconds == 1
if cur_speed == target_speed
return cur_speed
else
return nil
end
end
solutions = []
delta.times do |i|
res1 = solution(cur_speed+i+1, target_speed, delta, seconds-1)
if res1
solutions << res1+cur_speed
end
res2 = solution(cur_speed-i-1, target_speed, delta, seconds-1)
if res2
solutions << res2+cur_speed
end
end
if delta == 0
return cur_speed * seconds
end
unless solutions.empty?
return solutions.max
end
end
v1 = gets.chomp.to_i
v2 = gets.chomp.to_i
t = gets.chomp.to_i
d = gets.chomp.to_i
p solution(v1, v2, d, t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment