Question: Given an array of 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. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7).Answer the question in most efficient way.
Algorithm:
Loop for all elements in arr[] and maintain two sums incl and excl where incl = Max sum including the previous element and excl = Max sum excluding the previous element.
Loop for all elements in arr[] and maintain two sums incl and excl where incl = Max sum including the previous element and excl = Max sum excluding the previous element.
Max sum excluding the current element will be max(incl, excl) and max sum including the current element will be excl + current element (Note that only excl is considered because elements cannot be adjacent).
At the end of the loop return max of incl and excl.
package com.examples.ajay;
public class MaxSumNoAdjacentElement {
private static int max(int i, int j) {
// TODO Auto-generated method stub
if(i < j) return j;
else return i;
}
private static void findSum(int[] array) {
// TODO Auto-generated method stub
int inclusive = array[0];
// Max sum including current element. (If current included, prev have to be excluded)
// Max sum including current element. (If current included, prev have to be excluded)
int exclusive = 0;
// Max sum excluding current element : max (prev-incl, prev-excl)
// Max sum excluding current element : max (prev-incl, prev-excl)
for(int i = 1; i< array.length; i++){
int temp = inclusive;
inclusive = exclusive + array[i];
exclusive = max(exclusive, temp);
}
System.out.println("Result : "+ max(inclusive, exclusive));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = {5, 5, 10, 40, 50, 35};
findSum(array);
}
}
No comments:
Post a Comment