atcoder educational dp problem a runtime error problem

  c++, dynamic-programming

I am getting a runtime error in some test cases when I try to submit my code.
Problem Link: https://atcoder.jp/contests/dp/tasks/dp_a

My code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
 
int minCost(int n, vector<int> h, vector<int> dp) {
 
    if (dp[n] != -1) {
        return dp[n];
    }
    if (n == 1) {
        return dp[n] = 0;
    }
    if (n == 2) {
        return dp[n] = abs(h[1] - h[2]);
    }
 
    int oneStep = minCost(n - 1, h, dp) + abs(h[n] - h[n - 1]);
    int twoStep = minCost(n - 2, h, dp) + abs(h[n] - h[n - 2]);
 
    if (oneStep < twoStep) {
        return dp[n] = oneStep;
    }
    return dp[n] = twoStep;
}
 
int32_t main() {
 
    int n;
    cin >> n;
    vector<int> h(n + 1);
    for (int i = 1; i <= n; i++) {
        cin >> h[i];
    }
    vector<int> dp(n + 1, -1);
    cout << minCost(n, h, dp);
 
    return 0;
}

i cannot figure out why it is giving runtime error. it works perfectly fine for sample tests.

Source: Windows Questions C++

LEAVE A COMMENT