码迷,mamicode.com
首页 > 其他好文 > 详细

[Coding Made Simple] Maximum Sum Subsequence Non-adjacent

时间:2017-08-22 13:55:00      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:null   pre   mat   log   other   new   dynamic   lis   imu   

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

标签:null   pre   mat   log   other   new   dynamic   lis   imu   

原文地址:http://www.cnblogs.com/lz87/p/7288855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!