Skip to content

Instantly share code, notes, and snippets.

@blurredbits
Last active December 20, 2015 00:29
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 blurredbits/6042490 to your computer and use it in GitHub Desktop.
Save blurredbits/6042490 to your computer and use it in GitHub Desktop.
Stakeout Solution

#Stakeout

Congratulations! You are the new elite hacker in a group of villainous ne'er-do-wells.

Luckily this group is more saavy than your last band of ruffians, and they are looking to software (and you) to improve their take. The con man for the team, has gone door-to-door down each street posing as a termite inspector so he could covertly total the valuable goods in each house. Normally the gang would just rob all the valuable homes, but there's a catch! Whenever a house is robbed in this wealthy neighborhood, the police watch it and the neighboring houses for months.

So the gang can't simply rob all the homes, and if they choose to rob one, they can no longer rob the house on either side of it.

The ringleader wants to know what houses he should rob to maximize the team's profit, and he wants to know now. Write a function that takes in an array of positive integers (home values) and returns the maximum expected value of robbing that street.

For example:

[ 20, 10, 50, 5, 1 ] should return $71, as robbing the first, third, and fifth houses is optimal [ 20, x, 50, x, 1 ]

[ 20, 50, 10, 1, 5 ] should return $55, as robbing the second and fifth houses is optimal [ x, 50, x, x, 5 ]

def payday(home_values, total = 0)
  if home_values.inject(:+) == 0
    return total;
  else
    total += home_values.max
    payday(fill_in_zero(home_values, home_values.index(home_values.max)), total)
  end
end

def fill_in_zero(array, start_index)
  array[start_index] = 0

  if start_index <= array.size
    array[start_index + 1] = 0
  end

  if start_index > 0
    array[start_index - 1] = 0
  end

  return array
end

puts payday([20,10,50,5,1,89,32,65])
puts payday([20,50,10,1,5,14,22,46])
@arunsivasankaran
Copy link

try [3,4,3,1]

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