fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6.  
  7. int n = sc.nextInt();
  8. int k = sc.nextInt();
  9.  
  10. long[] a = new long[n + 1];
  11. for (int i = 1; i <= n; i++) {
  12. a[i] = sc.nextLong();
  13. }
  14.  
  15. long[][] dp = new long[n + 1][k + 1];
  16. long NEG_INF = Long.MIN_VALUE / 4;
  17.  
  18. for (int i = 0; i <= n; i++) {
  19. Arrays.fill(dp[i], NEG_INF);
  20. }
  21.  
  22. dp[1][1] = a[1];
  23. dp[1][0] = 0;
  24. dp[2][0] = 0;
  25. dp[2][1] = Math.max(a[1], a[2]);
  26.  
  27. for (int i = 3; i <= n; i++) {
  28. dp[i][0] = 0;
  29.  
  30. for (int j = 1; j <= k; j++) {
  31. dp[i][j] = Math.max(
  32. dp[i - 1][j],
  33. a[i] + dp[i - 2][j - 1]
  34. );
  35. }
  36. }
  37.  
  38. System.out.println(dp[n][k]);
  39. sc.close();
  40. }
  41. }
Success #stdin #stdout 0.16s 54368KB
stdin
5 2 
1 2 3 4 5
stdout
8