House Robber
Problem
A row of houses has money a[i]. You can not rob two neighbouring houses. Read the array and print the largest amount you can rob.
Constraints
- 1 <= n <= 10^5
- 0 <= a[i] <= 10^4
Examples
Input
4 1 2 3 1
Output
4
Solutions
At each house there are two choices. The best answer for the first i houses is max(best for i - 1, best for i - 2 + a[i]). Two variables are enough.
/*
* Problem : Maximum robbery.
* Input : n, then n integers.
* Output : The largest sum.
* Approach: Skip it or take it.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: skipLast = best amount when the last house is not robbed. takeLast = best amount up to the last house.
long skipLast = 0;
long takeLast = 0;
for (int money : a) {
// Step 2: For this house we either skip it (keep the best so far), or rob it (add to the best before the last house).
long best = Math.max(takeLast, skipLast + money);
skipLast = takeLast;
takeLast = best;
}
return takeLast;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- Which two earlier results does the answer for house i need?