คำอธิบายโจทย์
อาร์เรย์ A กระโดดจาก i ไป j (i A = [10,13,12,14,15] → Output: 2 (index 3 และ 4) Monotonic Map + DP:ตัวอย่าง
วิธีแก้ปัญหา
การทำงานของโค้ด
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int oddEvenJumps(vector<int>& A) {
int ret = 1, n = A.size();
vector<int> nextGE(n, -1), nextSE(n, -1);
map<int, int> st; // value -> index
for(int i=n-1; i>=0; i--) {
auto it = st.lower_bound(A[i]);
nextGE[i] = (it != st.end()) ? it->second : -1;
if(it != st.end() && it->first == A[i]) it++;
nextSE[i] = (it != st.begin()) ? prev(it)->second : -1;
st[A[i]] = i;
}
vector<vector<bool>> v(n, vector<bool>(2, false));
v[n-1][0] = v[n-1][1] = true;
for(int i=n-2; i>=0; i--) {
if(nextGE[i] != -1) v[i][1] = v[nextGE[i]][0];
if(nextSE[i] != -1) v[i][0] = v[nextSE[i]][1];
if(v[i][1]) ret++;
}
return ret;
}
};
int main() {
Solution ob;
vector<int> v = {10,13,12,14,15};
cout << ob.oddEvenJumps(v);
return 0;
}
อินพุต
{10,13,12,14,15}
เอาต์พุต
2