3
void tryOddJump(const int idx, const int val, std::map<int, int> &visitedNode,4
vector<int> &oddJumpsDP, vector<int> &evenJumpsDP) {5
// looking for equal or bigger element and it's going to be smallest posible6
auto jumpPoint = visitedNode.lower_bound(val);7
// If from jumpPoint exists even jump further, then odd jump will have some9
if (jumpPoint != visitedNode.end()) oddJumpsDP[idx] = evenJumpsDP[jumpPoint->second];12
void tryEvenJump(const int idx, const int val, std::map<int, int> &visitedNode,13
vector<int> &oddJumpsDP, vector<int> &evenJumpsDP) {14
// looking for strictly bigger element because then I can be sure that15
// previous will be equal or less that val for sure16
auto jumpPoint = visitedNode.upper_bound(val);17
// if it's first element, then there is no equal or less option, so no even19
if (jumpPoint != visitedNode.begin())20
evenJumpsDP[idx] = oddJumpsDP[std::prev(jumpPoint)->second]; // (jumpPoint-1) check if21
// further odd jump is22
// possible from largest23
// element that is <= val27
int oddEvenJumps(vector<int> &arr) {28
const size_t n = arr.size();29
vector<int> oddJumpsDP(n, 0);30
vector<int> evenJumpsDP(n, 0);31
oddJumpsDP[n - 1] = 1;32
evenJumpsDP[n - 1] = 1;33
std::map<int, int> visitedNode;34
visitedNode[arr[n - 1]] = n - 1;37
Idea is to move backward and keep track of posibility of odd and even jumps38
from each cell. This way at any jump we could check if further jumps is41
arr = [10,13,12,14,15]42
odd = [ -, -, 0, 1, 1]43
even= [ -, -, -, 0, 1]45
Let's say we curently have answers for 14 and 15 and trying to work on46
12: tryOddJump() -> will give us 14 as only possible odd jump(arr[i] <=47
arr[j] and arr[j] is the smallest possible value), but there is no EVEN jump48
from 14 further, so we cache odd jump for 12 as 0 as well. That's why I49
called thouse variables as oddJumpsDP/evenJumpsDP, they are caches for50
subproblems that helps in later computations. Without them we would need to51
check entire further path starting from each cell and it's not efficient.54
for (int i = n - 2; i >= 0; --i) {55
tryOddJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP);56
tryEvenJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP);57
// we alwayse start from 1st jump that is odd jump, so we can add index to58
// the result if odd jump from it is possible59
if (oddJumpsDP[i] == 1) ++res;60
visitedNode[arr[i]] = i;