Skip to content

Instantly share code, notes, and snippets.

@richardwei6
Created September 21, 2021 04:43
Show Gist options
  • Save richardwei6/e8ca24c147d55c857c18d85c9e482a8b to your computer and use it in GitHub Desktop.
Save richardwei6/e8ca24c147d55c857c18d85c9e482a8b to your computer and use it in GitHub Desktop.
LongJumps.cpp
int solution(vector<int> a) {
int n = a.size();
vector<int> dp(n, 0); // init array of size n to 0
int mx = 0; // find max dp value
for (int i = n - 1; i > -1; i--) { // loop backwards from a
int t = a[i]; // this DP value
int nextIndex = i + a[i]; // see if DP value from next jump exists
if (nextIndex < n) {
t += dp[nextIndex]; // DP value exists, add to this DP value
}
dp[i] = t; // set DP value
mx = max(mx, dp[i]); // take the max dp value found
}
return mx;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment