fork download
  1. //You are given an array of N integers (both positive and negative).
  2. //You can either take an element and add it to your sum or skip it.
  3. //However, if you take an element, you must skip the next K elements.
  4. //Find the maximum sum you can obtain.
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7.  
  8. int main() {
  9. int n,k;cin>>n>>k; int arr[n];
  10. for(int i=0;i<n;i++)
  11. cin>>arr[i];
  12.  
  13. vector<int>dp(n,0);
  14. dp[0]=arr[0];
  15. for(int i=1;i<=k;i++)
  16. dp[i]=max(arr[i], dp[i-1]);
  17. for(int i=k+1;i<n;i++){
  18. dp[i]=max(arr[i]+dp[i-k-1], dp[i-1]);
  19. }
  20. cout<<dp[n-1]<<endl;
  21. return 0;
  22. }
Success #stdin #stdout 0.01s 5292KB
stdin
15
4
2
-5
8
4
9
12
-8
-2
4
-1
6
8
-9
4
7
stdout
22