The Maximum Sum Subsequence with Non-Adjacent Elements and Constraints problem is to find the maximum sum of a subsequence in an array of non-negative integers, where no adjacent elements in the subsequence are allowed and the subsequence must satisfy some additional constraints.
To solve this problem using dynamic programming, we can define an array ‘dp‘ where ‘dp[i]‘ represents the maximum sum of a non-adjacent subsequence ending at index ‘i‘. We can start the array with ‘dp[0] = arr[0]‘ and ‘dp[1] = max(arr[0], arr[1])‘.
For each subsequent index ‘i‘ in the array, we can have two possible scenarios:
1. We include ‘arr[i]‘ in the subsequence. In this case, we cannot include ‘arr[i-1]‘ in the subsequence, so we need to look at ‘dp[i-2]‘ (since ‘dp[i-1]‘ would contain adjacent element ‘arr[i-1]‘). The maximum sum must be ‘arr[i] + dp[i-2]‘, so we can set ‘dp[i] = arr[i] + dp[i-2]‘ in this case.
2. We exclude ‘arr[i]‘ from the subsequence. In this case, we can consider the maximum sum that can be achieved up to index ‘i-1‘, which is ‘dp[i-1]‘. So ‘dp[i] = dp[i-1]‘ in this case.
Finally, the maximum sum of a non-adjacent subsequence in the array would be the maximum value in the ‘dp‘ array, which can be obtained by iterating through the array and keeping track of the maximum value seen.
Here is the Java code to implement this solution:
public int maxSumNonAdjacent(int[] arr) {
int n = arr.length;
int[] dp = new int[n];
dp[0] = arr[0];
dp[1] = Math.max(arr[0], arr[1]);
for (int i = 2; i < n; i++) {
// Include arr[i] in subsequence
int sum1 = arr[i] + dp[i-2];
// Exclude arr[i] from subsequence
int sum2 = dp[i-1];
// Take maximum of the two cases
dp[i] = Math.max(sum1, sum2);
}
// Find maximum value in dp array
int maxSum = dp[0];
for (int i = 1; i < n; i++) {
maxSum = Math.max(maxSum, dp[i]);
}
return maxSum;
}
Let’s take an example of an array ‘[1, 2, 3, 1]‘.
- For ‘i=0‘, ‘dp[0] = 1‘.
- For ‘i=1‘, ‘dp[1] = 2‘ (since we can choose either ‘1‘ or ‘2‘ as maximum sum contiguous subsequence).
- For ‘i=2‘, we can either include or exclude ‘3‘. If we include it, the maximum sum that can be achieved till this index is ‘dp[0] + 3 = 4‘. If we exclude it, the maximum sum that can be achieved till this index is ‘dp[1] = 2‘. So ‘dp[2] = 4‘.
- For ‘i=3‘, we can either include or exclude ‘1‘. If we include it, the maximum sum that can be achieved till this index is ‘dp[1] + 1 = 3‘. If we exclude it, the maximum sum that can be achieved till this index is ‘dp[2] = 4‘. So ‘dp[3] = 4‘.
Therefore, the maximum sum of a non-adjacent subsequence in the array is ‘4‘.