Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/7-misc/dp_opt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,25 @@ int main() {
f(i, 0, n, 0, n);
// output
cout << dp[m][n];
}
}

// 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<ll> a) {
ll ret = 0;
priority_queue<ll> 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;
}