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. long P = sc.nextLong();
  10.  
  11. long[] a = new long[n + 1];
  12.  
  13. for (int i = 1; i <= n; i++) {
  14. a[i] = sc.nextLong();
  15. }
  16.  
  17. long NEG_INF = Long.MIN_VALUE / 4;
  18.  
  19. long[][] dp = new long[n + 1][k + 1];
  20.  
  21. for (int i = 0; i <= n; i++) {
  22. Arrays.fill(dp[i], NEG_INF);
  23. }
  24.  
  25. dp[0][0] = 0;
  26.  
  27. for (int i = 1; i <= n; i++) {
  28. dp[i][0] = 0;
  29.  
  30. for (int j = 1; j <= k; j++) {
  31.  
  32. // Don't take i
  33. dp[i][j] = dp[i - 1][j];
  34.  
  35. // Take i, but don't take i-1
  36. if (i >= 2 && dp[i - 2][j - 1] != NEG_INF) {
  37. dp[i][j] = Math.max(
  38. dp[i][j],
  39. a[i] + dp[i - 2][j - 1]
  40. );
  41. }
  42.  
  43. // Take both i-1 and i -> pay penalty P
  44. if (i >= 2 && j >= 2 && dp[i - 2][j - 2] != NEG_INF) {
  45. dp[i][j] = Math.max(
  46. dp[i][j],
  47. a[i] + a[i - 1] - P + dp[i - 2][j - 2]
  48. );
  49. }
  50. }
  51. }
  52.  
  53. System.out.println(dp[n][k]);
  54.  
  55. sc.close();
  56. }
  57. }
Success #stdin #stdout 0.11s 54384KB
stdin
4 3 4
1 2 3 1 
stdout
2