From 870cfff256d2b8f06a9696eec32a014685f96b8f Mon Sep 17 00:00:00 2001 From: manoflearning <77jwk0724@gmail.com> Date: Thu, 27 Nov 2025 22:59:33 +0900 Subject: [PATCH] feat: add slope trick --- src/7-misc/dp_opt.cpp | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) 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; +}