Slope Hack ((install)) Here
What is the Slope Hack? The slope hack (also known as the "convex trick" or "slope trick" in competitive programming) is a technique for optimizing DP (Dynamic Programming) transitions of the form:
Slope trick code (C++):
[ dp[i] = \min_j < i (dp[j] + |a_i - a_j| \cdot C + \textconstant) ] slope hack
#include <bits/stdc++.h> using namespace std; int main() int n; cin >> n; What is the Slope Hack
for (int i = 1; i <= n; i++) long long x; cin >> x; x -= i; // transform to non-decreasing problem // Add using namespace std
priority_queue<long long> left; // max-heap priority_queue<long long, vector<long long>, greater<long long>> right; // min-heap long long ans = 0;