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 Main
  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. int[] a = new int[n];
  16. for(int i=0;i<n;i++){
  17. a[i] = sc.nextInt();
  18. }
  19. if (n < 2) {
  20. System.out.println(0);
  21. return;
  22. }
  23.  
  24. int[][] dp = new int[n][2];
  25. int[][] pre = new int[n][2];
  26.  
  27.  
  28. dp[0][0] = Integer.MIN_VALUE;
  29. dp[0][1] = Integer.MIN_VALUE;
  30. dp[1][0] = a[0] + a[1];
  31. dp[1][1] = Integer.MIN_VALUE;
  32.  
  33. pre[0][0] = dp[0][0];
  34. pre[0][1] = dp[0][1];
  35. pre[1][0] = dp[1][0];
  36. pre[1][1] = dp[1][1];
  37.  
  38. int ans = dp[1][0];
  39.  
  40. for(int i=2;i<n;i++){
  41. int p1 = a[i] + a[i-1] + ((i-3>=0) ? dp[i-3][0] : 0);
  42. int p2 = a[i] + a[i-1];
  43. if(i-4>=0){
  44. p2 += Math.max(pre[i-4][0], pre[i-4][1]);
  45. }
  46. dp[i][0] = Math.max(p1, p2);
  47.  
  48. dp[i][1] = a[i] + a[i-1] + a[i-2];
  49. if(i-5 >= 0){
  50. dp[i][1] += Math.max(pre[i-5][0], pre[i-5][1]);
  51. }
  52.  
  53. pre[i][0] = Math.max(pre[i-1][0], dp[i][0]);
  54. pre[i][1] = Math.max(pre[i-1][1], dp[i][1]);
  55.  
  56. ans = Math.max(ans, Math.max(dp[i][0], dp[i][1]));
  57. }
  58. System.out.println(ans);
  59.  
  60. }
  61. }
Success #stdin #stdout 0.11s 54512KB
stdin
4
1 2 3 4
stdout
9