fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n,a[100001],k, dp[100001];
  4. void nhap()
  5. {
  6. cin >> n;
  7. for(int i = 1; i <= n; i++) cin >> a[i];
  8. cin >> k;
  9. }
  10. void solve()
  11. {
  12. dp[0] = 0, dp[1] = a[1];
  13. if(k == 1)
  14. {
  15. dp[2] = max(a[1], a[2]);
  16. for(int i = 3; i <= n; i++)
  17. {
  18. dp[i] = max(dp[i-2] + a[i], dp[i-1]);
  19. }
  20. if(dp[n] < 0) cout <<0;
  21. else cout << dp[n];
  22. }
  23. else
  24. {
  25. dp[2] = max(a[2], dp[1] + a[2]);
  26. for(int i = 3; i <= n; i++)
  27. {
  28. dp[i] = max(a[i] + a[i-1] + dp[i-3], max(dp[i-2] + a[i], dp[i-1]));
  29. }
  30. if(dp[n] < 0) cout<< 0;
  31. else cout << dp[n];
  32. }
  33. }
  34. int main()
  35. {
  36. ios_base::sync_with_stdio(0);
  37. cin.tie(0); cout.tie(0);
  38. nhap();
  39. solve();
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0.01s 5292KB
stdin
5 
6 9 1 3 5 2
2
stdout
23