#### Problem

Finding the maximum subsequence sum such that non of the elements in the sequence are adjacent to each other#### Approach

One brute force approach is getting all the combinations, and excluding any combination with adjacent elements and finding the maximum from the remaining combinations. Obviously the approach is exponential. Below is the solution to solve the problem using Dynamic Programming.

In-order to solve a problem using dynamic programming there should be a solution which has optimal substructure and overlapping sub problems properties. And the current problem has optimal substructure property.

Say, f( i) is defined as maximum subsequence sum of non adjacent elements for 'i' items, then

then

f( i) = 0 if i = 0

Below is the algorithm for the same (note it can solved without the encapsulating data in 'record' - i just preferred it this way) - which should illustrate the above idea:

Code Snippet

- int FindMaxNonAdjuscentSubsequentSum(int[] a)
- {
- a.ThrowIfNull("a");
- if(a.Length == 0)
- {
- return 0;
- }
- Record r = new Record()
- {
- max_including_item = a[0],
- max_excluding_item = 0
- };
- for (int i = 1; i < a.Length; i++)
- {
- var t = new Record();
- //there will be only two cases
- //1. if it includes the current item, max is maximum of non adjuscent sub
- //sequence sum so far, excluding the last item
- t.max_including_item = r.max_excluding_item + a[i];
- //2. if it excludes current item, max is maximum of non adjuscent subsequence sum
- t.max_excluding_item = r.Max;
- r = t;
- }
- return r.Max;
- }

#### Unit Tests

Code Snippet

- [TestMethod]
- [TestCategory(Constants.DynamicProgramming)]
- public void MaxNonAdjascentSubsequenceSum()
- {
- int[] a = new int[] { 3, 2, 5, 10, 7};
- Assert.IsTrue(15 == this.FindMaxNonAdjuscentSubsequentSum(a));
- a = new int[] { 3, 2, 5, 10 };
- Assert.IsTrue(13 == this.FindMaxNonAdjuscentSubsequentSum(a));
- a = new int[] { 5, 10, 40, 50, 35 };
- Assert.IsTrue(80 == this.FindMaxNonAdjuscentSubsequentSum(a));
- a = new int[] { 1, -1, 6, -4, 2, 2 };
- Assert.IsTrue(9 == this.FindMaxNonAdjuscentSubsequentSum(a));
- a = new int[] { 1, 6, 10, 14, -5, -1, 2, -1, 3 };
- Assert.IsTrue(25 == this.FindMaxNonAdjuscentSubsequentSum(a));
- }

#### Helpers

Code Snippet

- public static int Max(int a, int b)
- {
- return (a > b) ? a : b;
- }
- class Record
- {
- public int max_including_item = int.MinValue;
- public int max_excluding_item = int.MinValue;
- public int Max
- {
- get
- {
- return Max(max_including_item, max_excluding_item);
- }
- }
- }

## No comments:

## Post a Comment