fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int getSum(vector<int>arr,int n){
  4. vector<int>dp(n,0);
  5. dp[0]=arr[0];
  6. dp[1]=dp[0]+arr[1];
  7. dp[2]=max(dp[0]+arr[2],dp[1]+arr[2]);
  8. for(int i=3;i<n;i++){
  9. dp[i]=max({dp[i-1]+arr[i],dp[i-2]+arr[i],dp[i-3]+arr[i]}); //as we can make 1 or 2 jumps back and current element must be included
  10. }
  11. return dp[n-1];
  12. }
  13.  
  14. int main() {
  15. // your code goes here
  16. vector<int>arr={1,2,-1,3,4};
  17. int n=arr.size();
  18. cout<<"The maximum sum of all elements by performing required 1,2 or 3 jumps is:"<<getSum(arr,n);
  19. return 0;
  20. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
The maximum sum of all elements by performing required 1,2 or 3 jumps is:10