- Arrays, Dynamic Programming, Greedy, Mathematical

Minimum jumps required to reach all array elements using largest element

#include using namespace std;#define ar array  ar expand(int idx, vector& A){                  int l = idx – 1;    int r = idx + 1;              while (l >= 0) {          if ((int)(A[idx]) > A[l]) {            –l;        }        else {            break;        }    }      if (l < 0 || l == idx) {        l = -2;    }              while (r < (int)(A.size())) {        if ((int)A[idx] > A[r]) {            ++r;        }        else {            break;        }    }      if (r >= (int)(A.size()) || r == idx) {        r = -2;    }              return { l, r };}  vector minJumps(int N, vector& A){    vector ans(N, 0);              map mp;      map iToA;    map AToi;          int big = A[0];                  for (int i = 0; i < N; ++i) {        big = max({ big, A[i] });        mp[i] = expand(i, A);          iToA[i] = A[i];        AToi[A[i]] = i;    }          sort(A.begin(), A.end(), greater());      for (int i = 0; i < A.size(); ++i) {                          int m;                          if (A[i] == big) {            int cur = AToi[A[i]];            ans[cur] = 0;            continue;        }                          int cur = AToi[A[i]];        int l = mp[cur][0];        int r = mp[cur][1];          if (l >= 0 && r < N) {            m = min(ans[l], ans[r]) + 1;        }        else if (l < 0 && r < N) {            m = ans[r] + 1;        }        else if (l >= 0 && r >= N) {            m = ans[l] + 1;        }                          ans[cur] = m;    }          return ans;}  int main(){    vector arr = { 5, 1, 3, 4, 7 };    int N = arr.size();      vector out = minJumps(N, arr);          for (auto& it : out)        cout