Skip to content

Instantly share code, notes, and snippets.

@aarti
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarti/ad2f3ae1ab97957bfedd to your computer and use it in GitHub Desktop.
Save aarti/ad2f3ae1ab97957bfedd to your computer and use it in GitHub Desktop.
def max_slice(a)
max_start,max_end = 0,0
largest_sum = 0
curr_start,curr_end = 0,0
curr_sum = 0
for i in 0..a.length-1
if (curr_sum + a[i] < 0 ) then
curr_start = i+1
curr_sum = 0
elsif (curr_sum + a[i] > curr_sum) then
curr_sum = curr_sum + a[i]
curr_end = i
if (curr_sum > largest_sum) then
max_start, max_end = curr_start,curr_end
largest_sum = curr_sum
end
end
end
a[max_start..max_end]
end
p max_slice(a)
p max_slice([-3,39,2,-1,65])
p max_slice([12,-3,39,2,-1,65])
p max_slice([-5,35,39,2,-160,65])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment