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β.