diff --git a/src/7-misc/dp_opt.cpp b/src/7-misc/dp_opt.cpp index 9d93930..3dd0643 100644 --- a/src/7-misc/dp_opt.cpp +++ b/src/7-misc/dp_opt.cpp @@ -131,4 +131,25 @@ int main() { f(i, 0, n, 0, n); // output cout << dp[m][n]; -} \ No newline at end of file +} + +// 4. Slope Trick +// PROBLEM: You are given the array containing n integers. +// At one turn you can pick any element and increase or decrease it by 1. +// The goal is the make the array strictly increasing by making the minimum possible number of operations. +// TIME COMPLEXITY: O(n log(n)) +ll slope_trick(vector a) { + ll ret = 0; + priority_queue pq; + for (int i = 0; i < sz(a); i++) { + a[i] -= i; // Change strictly increasing condition to non-decreasing condition + pq.push(a[i]); + + if (pq.top() > a[i]) { + ret += pq.top() - a[i]; + pq.pop(); + pq.push(a[i]); + } + } + return ret; +}