Given an array of positive number, find maximum sum subsequence such that elements in this subsequence are not adjacent to each other.
Recursive formula: f(n) = Math.max{f(n - 1), f(n - 2) + arr[n - 1]}.
Dynamic programming is used to get rid of the overlapping subproblems.
State: T[i]: the max sum of non-adjacent subsequence from arr[0.... n - 1];
Function: T[i] = Math.max(T[i - 1], T[i - 2] + arr[i - 1]);
Init: T[0] = 0, T[1] = arr[0];
Answer: T[arr.length].
1 import java.util.ArrayList; 2 3 public class MaxSumSubsequence { 4 private ArrayList<Integer> subseq; 5 public int getMaxSumSubseqNonAdj(int[] arr) { 6 if(arr == null || arr.length == 0) { 7 return 0; 8 } 9 int[] T = new int[arr.length + 1]; 10 T[0] = 0; T[1] = arr[0]; 11 for(int i = 2; i < T.length; i++) { 12 T[i] = Math.max(T[i - 1], T[i - 2] + arr[i - 1]); 13 } 14 subseq = new ArrayList<Integer>(); 15 int currSum = T[arr.length]; 16 int idx = arr.length; 17 while(currSum != 0) { 18 if(idx >= 2) { 19 if(T[idx - 1] <= T[idx - 2] + arr[idx - 1]) { 20 subseq.add(arr[idx - 1]); 21 currSum -= arr[idx - 1]; 22 idx -= 2; 23 } 24 else { 25 idx--; 26 } 27 } 28 else { 29 subseq.add(arr[idx - 1]); 30 currSum -= arr[idx - 1]; 31 idx--; 32 } 33 } 34 return T[arr.length]; 35 } 36 }
时间: 2024-11-07 03:13:26