Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Rabbit Carrot

#include <bits/stdc++.h>
using namespace std;

const int inf = 1e5;

void solve(vector<int> &a, int m) {
    a.insert(a.begin(), 0);
    int n = a.size();

    // dp[i] is the minimum number of operations on the prefix [0 ... i]
    // such that the i-th element is retained.
    vector<int> dp(n, inf);
    dp[0] = 0;

    for (int i = 0; i < n; i++) {
        for (int j = i - 1; j >= 0; j--) {
            // Assume that j is the second last retained element.
            if (a[i] - a[j] <= (i - j) * m) {
                dp[i] = min(dp[i], dp[j] + i - j - 1);
            }
        }
    }

    int ans = n;
    for (int i = 0; i < n; i++) {
        // i-th element is the last retained element, all elements to the
        // right are deleted.
        ans = min(ans, dp[i] + (n - 1 - i));
    }

    cout << ans << endl;
}

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    solve(a, m);
    return 0;
}