[AlgoExpert] Max Subset Sum No Adjacent

Max Subset Sum No Adjacent

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>
using namespace std;

int helper(vector<int>& dp, vector<int>& A, int p) {
if(p >= A.size()) return 0;
if(dp[p] != -1) return dp[p];
dp[p] = A[p];
dp[p] = max(dp[p], A[p] + helper(dp, A, p + 2));
dp[p] = max(dp[p], A[p] + helper(dp, A, p + 3));

return dp[p];
}

int maxSubsetSumNoAdjacent(vector<int> array) {
vector<int> dp(array.size(), -1);
return max(helper(dp, array, 0), helper(dp, array, 1));
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/max-subset-sum-no-adjacent/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.