- Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathMaximumSumOfSubseqNonAdjacent.java
83 lines (54 loc) · 2.17 KB
/
MaximumSumOfSubseqNonAdjacent.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
https://www.techiedelight.com/maximum-sum-of-subsequence-with-no-adjacent-elements
This problem is similar to the concept of 0/1 Knapsack Problem. Each element can be included or excluded. All elements in the subseq must be non-adjacent.
*/
//Recursion
//Include the current element and exclude the current element. Choose the max value.
publicintmaxSumOfSubseqNonAdj(intA[], intcurrIndex, intprevIndex, intn){
//we have exhausted all elements of the array
if(currIndex == n) return0;
//exclude the current element
intexc = maxSumOfSubseqNonAdj(A, currIndex+1, prevIndex, n);
intinc = 0;
//include current element only if the it is not adjacent to the prev element considered in the subseq
if(prevIndex+1 != currIndex) inc = maxSumOfSubseqNonAdj(A, currIndex+1, currIndex, n) + A[currIndex];
//return the maximum sum possible
returnMath.max(inc, exc);
}
//Bottom Up Dynamic Programming
publicintmaxSumOfSubseqNonAdj(intA[]){
intn = A.length;
if(n == 1) returnA[0];
intsum[] = newint[n];
sum[0] = A[0];
sum[1] = Math.max(A[0], A[1]);
for(inti = 2 ; i < n ; i++){
intexc = sum[i-1];
intinc = sum[i-2] + A[i];
sum[i] = Math.max(exc, inc);
//Usefull if both inc, exc and A[i] are negative --> choose the maximum
sum[i] = Math.max(sum[i], A[i]);
}
returnsum[n-1];
}
//Time and Space Complexity - O(n)
//We require only two variables to compute current sum and not entire array
publicintmaxSumOfSubseqNonAdj(intA[]){
intn = A.length;
if(n == 1) returnA[0];
intprevPrevSum = A[0];
intprevSum = Math.max(A[0], A[1]);
for(inti = 2 ; i < n ; i++){
intexc = prevSum;
intinc = prevPrevSum + A[i];
intcurrSum = Math.max(inc, exc);
//Usefull if both inc, exc and A[i] are negative --> choose the maximum
currSum = Math.max(currSum, A[i]);
//Update previous values
prevPrevSum = prevSum;
prevSum = currSum;
}
returnprevSum;
}
//Time Complexity - O(n)
//Space Complexity - O(1)