Prompt
Write a function that takes in an array of positive integers and returns the maximum sum of non-adjacent elements in the array.
If a sum can’t be generated, the function should return 0 .
Sample Input
array = [75, 105, 120, 75, 90, 135]
Sample Output
330 // 75, 120, 135
Solution
import java.util.*;
class Program {
// O(n) time | O(n) space
public static int maxSubsetSumNoAdjacent(int[] array) {
if (array.length == 0) {
return 0;
} else if (array.length == 1) {
return array[0];
}
int[] sum = array.clone();
sum[0] = array[0];
sum[1] = Math.max(array[0], array[1]);
for (int i = 2; i < array.length; i ++) {
sum[i] = Math.max(sum[i - 1], sum[i - 2] + array[i]);
}
return sum[array.length - 1];
}
}
看来青蛙那个题的思想很常见