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. // your code goes here
  13. Scanner sc=new Scanner(System.in);
  14. int N=sc.nextInt();
  15.  
  16. // 1-based indexing
  17. int [] arr=new int [N+1];
  18.  
  19. for(int i=1;i<=N;i++){
  20. arr[i]=sc.nextInt();
  21. }
  22.  
  23. int [] dp=new int[N+1];
  24. if(arr[1]>0){
  25. dp[1]=arr[1];
  26. }else{
  27. dp[1]=0;
  28. }
  29. if(arr[2]>0){
  30. dp[2]=Math.max(dp[1],arr[2]);
  31. }else{
  32. dp[2]=0;
  33. }
  34. for(int i=3;i<=N;i++){
  35.  
  36. // no consecutive elements should be considered....
  37. dp[i]=Math.max(dp[i-2]+arr[i],dp[i-1]);
  38. }
  39. System.out.println("Answer : "+dp[N]);
  40. sc.close();
  41. }
  42. }
Success #stdin #stdout 0.14s 56984KB
stdin
5
1 -100 2 4 5
stdout
Answer : 8