All problems

Problem 181

House Robber

Medium · 20 pts · Array, Dynamic Programming

Problem

A robber plans to rob houses along a street. House i holds A[i] money. The houses have connected alarms, so robbing two adjacent houses on the same night calls the police. Find the largest total amount the robber can take without robbing two neighbouring houses. For each house, the best total up to it is either the best total up to the previous house (skip this one) or this house's money plus the best total up to two houses back (rob this one). So best[i] = max(best[i - 1], best[i - 2] + A[i]), computed in one pass.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the maximum amount.

Constraints

1 <= N <= 100000; 0 <= A[i] <= 10000

Example input

4
1 2 3 1

Example output

4

Explanation

In 1 2 3 1, robbing the 1st and 3rd houses gives 1 + 3 = 4. The other options, such as 2 + 1 = 3 from the 2nd and 4th houses, are smaller, so the answer is 4.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Tree Diameter Next: House Robber II