Idea: meisgood
Preparation: meisgood
$n \le 20$
Exhaust all position of cutting the array. Take the maximum.
Time complexity: $O(2^{n-1}\cdot n)$
$n \le 1000$
Let $dp[i]$ be the maximal value obtained by only considering $a[1…i]$.
While computing $dp[i]$, we can loop $j$ through $1$ to $i-1$ meaning we will cut out $a[j+1…i]$ as a new segment. Therefore we have a transition formula:
$dp[i] =$ max of $($
$dp[j]+sum(a[j+1…i])$ if $a[j+1] \le a[i]$
$dp[j]-sum(a[j+1…i])$ if $a[j+1] \gt a[i]$
$)$ for all $j$ from $1$ to $i-1$.
The answer is $dp[n]$.
The transition can be done in $O(n)$ with careful implementation.
Time complexity: $O(n^2)$. Expected score: 50
Full Solution
We need to further optimize the transition.
Using prefix sum, we can replace $sum(a[l…r])$ by $ps[r]-ps[l-1]$. Apply it to the transition formula,
$dp[i]=$ max of $($
$dp[j]+ps[i]-ps[j-1])$ if $a[j+1] \le a[i]$
$dp[j]-ps[i]+ps[j-1])$ if $a[j+1] \gt a[i]$
$)$ for all $j$ from $1$ to $i-1$.
Therefore,
$dp[i]=max($
case 1: $max((dp[j]-ps[j-1]) + ps[i])$ for all previous $j$ with $a[j+1]$ in range $[-inf,a[i]]$
case 2: $max((dp[j]+ps[j-1]) - ps[i])$ for all previous $j$ with $a[j+1]$ in range $[a[i]+1,inf]$
$)$
Solution 1:
Discretize a and handle the transition by maintaining one segment tree for case 1 and one for case 2. Every time when done computing $dp[i]$, update position $a[i+1]$ with value $dp[i]-ps[i-1]$ for case 1 and $dp[i]+ps[i-1]$ for case 2. for computing the dp values, do range queries for both cases and take the maximum.
Time complexity: $O(nlogn)$. Expected score: 100 (75 without discretization)
Solution 2:
Use similar idea of monotonic queue but using set for doing prefix/suffix maximum queries with update.
Time complexity: $O(nlogn)$. Expected score: 100
Reminder
Remember to use long long or else you can only score 45 even with the full solution!