Question : Given an array all of whose elements are positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.
Eg.
i) 3 2 7 10 should return 13 (sum of 3 and 10)
ii) 3 2 5 10 7 should return 15 (sum of 3, 5 and 7)
The idea is to use Dynamic Programming and store the intermediate “good” sums in an auxiliary array. The right way is to define an array B[n] whose j-th element B[j] represents the best sum that has A[j] as the last element.
A simplistic java code looks like this :
public class maxSkip
{
public static void main(String args[])
{
.... int[] a = {3,2,5,10,7};
.... int j,mx=0;
.... int len = a.length;
.... int[] b = new int[len];
....b[0] = a[0]; if(len==1) mx = b[0];
....b[1] = a[1]; if(len==2) mx = max(b[0],b[1]);
....b[2] = a[2]+b[0]; if(len==3) mx = max(b[1],b[2]);
.... for(j = 3 ; j< len; j++)
.... {
........ b[j] = max(a[j]+b[j-2] , a[j] + b[j-3]);
.... }
.... mx= max(b[j-2], b[j-1]);
.... System.out.println("Max subsequence : " + mx);
}
public static int max(int a, int b)
{
......return(a>b?a:b);
}
}
Eg.
i) 3 2 7 10 should return 13 (sum of 3 and 10)
ii) 3 2 5 10 7 should return 15 (sum of 3, 5 and 7)
The idea is to use Dynamic Programming and store the intermediate “good” sums in an auxiliary array. The right way is to define an array B[n] whose j-th element B[j] represents the best sum that has A[j] as the last element.
A simplistic java code looks like this :
public class maxSkip
{
public static void main(String args[])
{
.... int[] a = {3,2,5,10,7};
.... int j,mx=0;
.... int len = a.length;
.... int[] b = new int[len];
....b[0] = a[0]; if(len==1) mx = b[0];
....b[1] = a[1]; if(len==2) mx = max(b[0],b[1]);
....b[2] = a[2]+b[0]; if(len==3) mx = max(b[1],b[2]);
.... for(j = 3 ; j< len; j++)
.... {
........ b[j] = max(a[j]+b[j-2] , a[j] + b[j-3]);
.... }
.... mx= max(b[j-2], b[j-1]);
.... System.out.println("Max subsequence : " + mx);
}
public static int max(int a, int b)
{
......return(a>b?a:b);
}
}
0 comments:
Post a Comment