[Coding Made Simple] Maximum Sum Subsequence Non-adjacent
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Coding Made Simple] Maximum Sum Subsequence Non-adjacent相关的知识,希望对你有一定的参考价值。
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 }
以上是关于[Coding Made Simple] Maximum Sum Subsequence Non-adjacent的主要内容,如果未能解决你的问题,请参考以下文章
[Coding Made Simple] Longest Increasing Subsequence
[Coding Made Simple] String Interleaving
[Coding Made Simple] Matrix Chain Multiplication
[Coding Made Simple] Burst Balloon