fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // -1,0,3,5,9,12
  13. int arr[]={2,4,6,7,8};
  14. int res = maximumSubsetExcludingAdjacent(arr);
  15. System.out.println(res);
  16. }
  17.  
  18. public static int maximumSubsetExcludingAdjacent(int[] arr){
  19.  
  20. int []dp =new int[arr.length];
  21. dp[0]=arr[0];
  22. dp[1]=Math.max(dp[0],arr[1]);
  23. for(int i=2;i<arr.length; i++){
  24. dp[i] = Math.max(dp[i-1],arr[i]+dp[i-2]);
  25. }
  26.  
  27. return dp[arr.length-1];
  28.  
  29. }
  30. }
Success #stdin #stdout 0.06s 54604KB
stdin
Standard input is empty
stdout
16