#Problem

#⭐️⭐️⭐️⭐️

求一个array中非连续元素能组成的最大sum.

#Solution

Dynamic Programming

dp[i] represents the maximum sum ending with i-th element.

dp[i] = Math.max(dp[i - 1], dp[i - 2] + A[i]);

#Code

#Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int maxSumWithoutAdjacentElements(int[] A) {
if (A.length == 1) return A[0];
int n = A.length;
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = A[i];
}
int res = Math.max(A[0], A[1]);
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i], dp[i - 2] + A[i]);
dp[i] = Math.max(dp[i], dp[i - 1]);
res = Math.max(dp[i]);
}
return res;
}
}

Comments