I recently encountered this problem:
In the challenge, you are given an array of n numbers and an integer k. In one minute, you can change any element of the array to any integer you want. Find the minimum amount of time you have to spend so that the following condition is satisfied: for all i from to 1, n - 1, a[i] - a[i - 1] = k. Since n, k <= 10^5 the solution should be linear (O(n)) or maybe O(n * logn) which I doubt.
I greedy and realized that this problem is probably DP, but I couldn't find an answer. This topic is similar, but the answers there are not of use (in my opinion). I'm just looking for a pseudo (or cpp) code.
UPD: I code a brute force solution in O(n^2), if it helps you here is the code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pi> vp;
typedef vector<pl> vpl;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cerr.tie(nullptr);
int n, k;
cin >> n >> k;
vi a(n);
for (auto& i : a)
cin >> i;
int res = INT32_MAX;
for (int i = 0; i < n; ++i){
int s = a[i], sol = 0;
for (int j = i + 1; j < n; ++j){
s += k;
if (a[j] != s)
++sol;
}
s = a[i];
for (int j = i - 1; j > -1; --j){
s -= k;
if (a[j] != s)
++sol;
}
res = min(sol, res);
}
cout << res << '\n';
}