We are given: n buildings, initial heights xi (positive integers). We can increase height by 1 for cost P, decrease by 1 for cost M. Final heights must be integers (so we can adjust arbitrarily). For each adjacent pair (i,i+1) such that they end up with equal height, we get a profit of S. Net profit = total bonus profit (S * number of equal adjacent pairs) minus total modification cost.
Goal: maximize net profit.
We need to output maximum net profit.
Constraints: n up to 2500, xi up to 1e6, S,P,M up to 1e9. So we need O(n * something) maybe O(n * H) where H can be large (up to 1e6) but perhaps we can compress heights.
We need to choose final heights hi (integers) for each building, minimizing total cost = sum_i cost_i(hi) - S * (#equal adjacent pairs) (since net profit = bonus - cost, we want to maximize bonus - cost, i.e., minimize cost - bonus; so it's like we have a cost function with negative profit for equal pairs). So we can think of minimizing total cost = sum_i C_i(hi) - S * sum_{i=1}^{n-1} I(hi == hi+1). Alternatively, think of net profit = - (total cost) + S * (#equal pairs). So maximize net profit = maximize (S * (#equal) - total modification cost). So it's a kind of DP with states being possible heights.
But heights can be large. However, we can note that final optimal heights will likely be among the initial heights, because adjusting to a height not present initially could be dominated. But careful: due to bonuses, maybe we want two adjacent buildings to have same height that is not equal to either's initial height? But maybe we can show that there exists an optimal solution where each final height is one of the original xi. Reason: The cost function for each building is convex piecewise linear with slopes P for increase, M for decrease. The overall objective includes pairwise indicator of equality. This is not a convex optimization, but we can argue: For a fixed set of final heights, suppose we have a building i with hi not equal to any xj. If we shift hi towards its original height by 1, the change in modification cost is either -P (if we decrease an increased height) or -M (if we increase a decreased height) depending on direction. And the effect on equalities with neighbors: if hi is equal to neighbor(s), changing it might break equality or create new ones. But it's not straightforward.
Nevertheless, typical approach for such problems: DP with states being possible heights, but we can compress to a set of candidate heights that includes all original xi, and possibly also some values in between for pairs? However, note that equality only matters for adjacency. The cost for each building is linear in distance from xi. So if we consider two adjacent buildings, the joint cost for them to have heights a and b is linear piecewise. The bonus S if a=b. So the optimal will tend to make some equalities.
We can think of this as a graph labeling problem with a unary cost (|hi - xi| * cost) and pairwise cost: for each edge (i,i+1), we have cost = -S if hi = hi+1 else 0? Actually net profit = S * 1(hi=hi+1) - sum_i cost_i(hi). So we want to minimize sum_i cost_i(hi) - S * sum_i 1(hi=hi+1). So it's like a Potts model with attractive bonus S for equality. This is NP-hard in general? But here the graph is a path, so we can solve using DP with states being hi. But hi domain is huge.
For path, we can do DP: dp[i][h] = minimum total cost (modification cost up to i, minus bonuses earned among edges up to i-1) given hi = h. Then transition: dp[i+1][h'] = min over h of dp[i][h] + cost_{i+1}(h') - S * 1(h == h'). Actually careful: The bonus for edge (i,i+1) is S if h == h'. So when we move to next building, we add the modification cost for building i+1 and subtract S if equality. So dp[i][h] includes cost for building i and bonuses for edges up to i-1. Then for i+1: dp[i+1][h'] = min_h { dp[i][h] + C_{i+1}(h') - S * (h == h') }. So we need to compute this efficiently.
If domain H is large, we need some structure to speed up min over h. This is like DP with cost that is either min_h dp[i][h] + C_{i+1}(h') (if no equality) but with a discount if h == h'. We can rewrite: dp[i+1][h] = C_{i+1}(h) + min( dp[i][h] - S, min_{k != h} dp[i][k] ). So dp[i+1][h] = C_{i+1}(h) + min( dp[i][h] - S, best_overall ) where best_overall = min_k dp[i][k]. However, if dp[i][h] - S is not the global min, we need to consider whether dp[i][h] - S could be less than best_overall? Actually it could be, but then min would be dp[i][h] - S. But if dp[i][h] - S > best_overall, then min = best_overall. However, there is a subtlety: if best_overall is achieved at some k != h, that's fine. But what if best_overall is exactly dp[i][h]? Then we need to ensure that we can use dp[i][h] - S which might be less than best_overall? But min( dp[i][h] - S, best_overall ) could be either. However, if best_overall = dp[i][h], then min is min(dp[i][h]-S, dp[i][h]) = dp[i][h]-S if S>0, which is less. But is that allowed? For h'=h, we can choose the same h for previous building, and we get the bonus S, so the cost contribution for transition is dp[i][h] + C_{i+1}(h) - S. That's exactly C_{i+1}(h) + (dp[i][h] - S). So it's valid. But if we use a different k for previous building, we add C_{i+1}(h) + dp[i][k] (no bonus). So overall, the recurrence is:
dp[i+1][h] = C_{i+1}(h) + min( dp[i][h] - S, min_{k} dp[i][k] )? Wait, careful: min over k != h of dp[i][k] is not necessarily equal to min_{k} dp[i][k] if the global min is at h. So we need to treat two cases: If the global min is at some height different from h, then min_{k != h} dp[i][k] = global min. If global min is at h, then min_{k != h} dp[i][k] is the second best (the minimum among others). So the recurrence is:
dp[i+1][h] = C_{i+1}(h) + min( dp[i][h] - S, min_{k != h} dp[i][k] ).
We can compute this efficiently if we can maintain for each i the array of dp[i][h] and be able to query the global minimum and the second minimum per value? Actually we need for each h the minimum over all other k. That is essentially: if we have the global minimum value m1 and its corresponding height h1, and the second minimum m2 (minimum among all heights except h1), then for any h:
- if h != h1, then min_{k != h} dp[i][k] = m1 (since m1 is at h1 which is not h) if m1 is not at h. Actually careful: if h != h1, then the global min m1 (at h1) is allowed because h1 != h. So min_{k != h} = m1.
- if h == h1, then min_{k != h} = m2 (since we cannot take the min at h itself). So we need global m1 and m2.
Thus dp[i+1][h] = C_{i+1}(h) + min( dp[i][h] - S, (h == h1 ? m2 : m1) ). So for each h we can compute in O(1) given we know dp[i][h] and global min and second min.
So the DP complexity becomes O(n * H) where H is number of distinct candidate heights. If we can restrict H to be manageable (maybe O(n) or O(n * something)), we can do it.
Now we need to determine candidate heights. Since we can choose any integer, but DP above uses a discrete set. Can we prove that optimal heights are among the initial xi? Let's examine.
Cost per building: C_i(h) = P * max(0, h - x_i) + M * max(0, x_i - h). This is piecewise linear, convex, with slope -M for h < x_i, slope P for h > x_i, and at h = x_i the cost is 0.
The DP recurrence uses only values of C_i(h) and dp[i][h]. The DP would be valid if we restrict to a set that includes all possible optimal values. Often for such problems with convex costs and Potts model on a path, the optimal solution can be found by considering only values from the set of initial xi. But is that always true? Consider two adjacent buildings i and i+1. Suppose we want them to be equal to some h that is not equal to either x_i or x_{i+1}. Could that be beneficial? Let's try a simple case: n=2, S is large, P and M. The net profit = S * 1(h1=h2) - (P*(h1-x1)+ + M*(x1-h1)+ + similar for building2). For maximizing net profit, we can decide whether to set them equal or not. If we set them equal to h, the total cost is cost1(h)+cost2(h)-S if we set equality. So we want to maximize S - cost1(h)-cost2(h) (if we set equal) or 0 - (cost1(h1)+cost2(h2)) maybe different. If S is large, we want to set equal to some h that minimizes cost1(h)+cost2(h). This minimizer is the weighted median? Actually cost1+cost2 is convex piecewise linear, with slopes: for h less than both, slope = -M-M = -2M; between x_i and x_j, slope changes; at exactly each x_i, there is a kink. The minimum of a convex function occurs at a point where derivative crosses zero. The derivative is -M * (# of buildings where h < x_i) + P * (# of buildings where h > x_i). For two buildings, the optimum is any h between the two medians? Actually for even count, the minimum occurs over an interval where derivative changes sign. Typically the minimizer is any h in [x_{(1)}, x_{(2)}] if we have equal weights? Let's compute: For two buildings with costs P and M, the function f(h) = c1(h)+c2(h). For h less than both x1 and x2, f' = -(M+M)= -2M (since both are above h, cost decreases as h increases). So f is decreasing. For h between x1 and x2, say x1 < h < x2, then building1: h > x1 so cost derivative = P; building2: h < x2 so derivative = -M; total derivative = P - M. If P - M > 0, then f is increasing; if P-M < 0, f is decreasing; if P=M, derivative 0, flat. For h > both, derivative = P+P=2P > 0. So the minimum occurs at the point where derivative changes from negative to positive. That is at one of the x_i if P-M>0? Actually if P-M>0, then for h in (x1, x2) derivative positive, so f increasing; for h < x1, derivative negative, so f decreasing. So minimum at h = x1 (the leftmost). If P-M<0, derivative negative in (x1,x2), so f decreasing until h=x2, then after that positive, so minimum at h=x2. If P=M, then derivative in (x1,x2) =0, flat, so any h between works. So the minimizer is at one of the initial heights (or any between if equal slopes). So indeed, the minimum of sum of convex piecewise linear costs occurs at one of the breakpoints, i.e., at the xi values. For multiple buildings, when we want to set a contiguous block to same height, the optimal common height minimizing total adjustment cost is the weighted median of the xi's with weights? Actually it's the minimizer of sum of absolute deviations with linear costs? More precisely, we have cost_i(h) = a_i * (h - x_i)+ + b_i * (x_i - h)+, where a_i = P, b_i = M. This is like asymmetric absolute loss. The minimizer is a quantile: the point where the sum of weights changes sign. But still the optimal h is at some x_i, because the function is convex piecewise linear with slopes changing at each x_i. So the minimum occurs at a point where the subgradient contains 0, which is at one of the x_i or any point in an interval between two x_i if slopes are zero on that interval. In that interval, all heights give same cost, but they are all between two x_i. However, if such an interval exists, then we could choose either endpoint (which is an x_i) without increasing cost? Actually if slopes on interval are zero, then cost is constant on that interval, so we can choose the endpoints also have same cost? But endpoints are at the x_i values, but the cost at x_i may be same as interior? Usually if derivative is zero on an interval, that means that for each building, if h is in that interval, the building's cost function derivative is either 0 if h exactly at its x_i? Let's analyze: For a building, derivative jumps at its x_i from -M to +P (or if P=M, then the jump is 2P?). Actually derivative from left is -M, from right is +P, at exact x_i the subgradient is [-M, P]. So the sum subgradient contains zero only if there is a combination that can sum to zero; it's possible at a point that is not an x_i only if some of the buildings have derivative continuous? But they are not continuous; they have kinks at each x_i. So the sum function's derivative is a step function that jumps at each x_i. The intervals between x_i have constant derivative (since each building's derivative is constant: either -M or +P depending if h is less than x_i or greater). So the derivative can be zero only at points where the sum of these constants is zero, which may hold for a range if the constants sum to zero over that range. That can happen if P and M are such that some combination yields zero? For example, with two buildings, if P=M, then derivative in (x1,x2) is P-M=0, so it's zero over the whole interval. So the cost function is constant on that interval, and endpoints at x1 and x2 may have the same cost? At x1, left derivative is something? Actually cost at x1: building1 cost 0, building2 cost = something. At interior point, building1 cost positive? Let's compute numeric: x1=1, x2=3, P=M=1. f(h) = |h-1| + |h-3|? Actually asymmetric? If P=M=1, then cost_i(h)=|h - x_i|. So f(h)=|h-1|+|h-3|. This is minimized on [1,3] with value 2. At h=1, cost = 0+2=2; at h=3, cost=2+0=2; at h=2, cost=1+1=2. So indeed constant on the interval, endpoints are also same. So choosing an endpoint (which is an x_i) yields same cost. So we can restrict to the set of xi's without loss of optimality for minimizing sum of adjustment costs for any subset of buildings set to equal height. However, in DP, we might not set all buildings equal, but DP transitions consider each building individually. But is it true that there exists an optimal solution where each hi belongs to the set of initial xi? This is typical for similar problems like "minimum cost to make array non-decreasing with increment/decrement costs" but there it's often the case that optimal heights are from the original values. Let's try to prove or find counterexample.
Suppose n=3, heights [1, 100, 1], S large, P=100, M=1. So raising is expensive, lowering is cheap. We might want to make adjacent equal to get bonuses, but perhaps we could lower the middle to 1, cost = (100-1)M=991=99, and also we might lower the left? Actually initial left is 1, right is 1. To get all three equal to 1, we lower middle from 100 to 1 costing 99, and get bonuses for edges: both edges equal, so total bonus 2S. Net profit = 2S - 99. Alternatively, we could raise left and right to something else? Since raising is expensive (P=100), maybe better to lower middle to something not exactly 1 but maybe 2? If we lower middle to 2, cost = (100-2)M=98, left and right are 1, then edges: (1,2) not equal, (2,1) not equal, no bonus. So that's bad. Could we make all three equal to 50? That would raise left by 49 cost 49100=4900, lower middle by 50 cost 50, raise right by 49 cost 4900, total cost 9850, no better. So best is equal to 1. So indeed final heights among original.
Consider scenario where P and M are different, and we have odd number of buildings, the optimal common height to minimize sum of costs is a weighted median; but that weighted median is one of the xi. So yes.
But in DP, each building's height is chosen sequentially, but the recurrence uses values from previous step. Could there be an optimal solution where some hi is not among any xj? Suppose we have two adjacent buildings i and i+1. Their heights affect cost and bonus. The DP essentially solves a Markov chain. It's known that for such problems with convex separable costs and pairwise equality bonuses on a path, the optimal solution can be found by considering only heights from the set of all xi. I recall similar problems: "Bricks" or "Making the grade" but there it's about making sequence non-decreasing with min cost, and the optimal heights are among the original values. That's due to convexity and the DP structure. For our problem, with equality bonus, it's like a "Potts model" with attractive potential, which is submodular? Actually indicator of equality is not submodular? But it's a pairwise term. However, we can convert to a segmentation perspective: The solution might consist of segments of consecutive buildings with equal height, and within each segment, the common height is chosen to minimize the sum of adjustment costs for those buildings. For each segment, the optimal common height (given that all buildings in the segment must have same height) is the minimizer of sum_i cost_i(h). As argued, that minimizer can be taken from the set of xi of buildings in that segment. So any optimal solution can be transformed such that each segment's common height is one of the xi from that segment. But could there be a scenario where a building is not in a segment of equality with its neighbors, i.e., its height is different from both neighbors? Then its height only affects its own cost, and the two edges do not give bonus. For such isolated building, the optimal height to minimize its own cost is simply its original height (since any deviation adds cost). So indeed, if a building is not equal to either neighbor, then it's optimal to keep it at its original height (since no benefit from deviating). However, it might be that a building is equal to one neighbor but not the other; then it belongs to a segment of length >=2. In that segment, the common height should minimize the sum of costs for that segment. So that common height can be chosen among the xi of that segment. So overall, there exists an optimal solution where every building's final height is equal to some original xj (maybe from its segment). But careful: Could it be that a building's height is not equal to any original xj if it's in a segment but the minimizer of sum of costs for that segment is not an original xj? As argued, the function sum_i cost_i(h) is convex piecewise linear with kinks at each xi. The minimum will be at a point where the subgradient contains zero, which may be an interval if the slopes sum to zero. But on such an interval, the cost is constant, so we can shift to either endpoint (which are original xi) without changing cost. So we can assume each segment's common height is some original xj. Moreover, if a building is not in any segment (i.e., isolated), its optimal height is its own original height (since cost_i is minimized at xi). So indeed all heights can be restricted to the set of all original xi (i.e., values that appear in the input). But is it possible that a segment's optimal height is not among the xi of that segment but rather an xi from another segment? Suppose we have segment [l..r] with common height h. The cost sum_{i=l}^{r} cost_i(h). The minimizer of this sum is a weighted median of the xi's, but it may be any xi (not necessarily within the segment)? Actually weighted median is some xi from the set of all values? For asymmetric absolute loss, the minimizer is any point where the cumulative weight of P and M cross. But it's known that for the problem min_h sum_i (a_i * (h - x_i)+), the optimal h is one of the x_i if a_i, b_i >=0. Because the objective is piecewise linear and changes slope only at x_i. So the minimum must occur at a point where the left derivative <= 0 <= right derivative. That is at some x_i. So yes, h is one of the x_i (maybe not from the segment? But x_i are from the segment because i ranges over l..r. So it's among those xi. So it's from that segment.
Thus we can restrict heights to the set of distinct values in the input. Let H be the set of distinct xi. The size D could be up to n (2500). So D <= 2500. That's manageable. DP with O(n * D) = 2500*2500 = 6.25 million, which is fine.
But careful: Could there be scenario where optimal height for a segment is not among the original xi but some value in between that yields same cost as at endpoints? As argued, we can replace by an endpoint (which is an original xi) without increasing cost. However, the endpoint must be among the xi of the segment. So it's fine.
But there is a nuance: The DP recurrence above uses all possible heights for each building, and transitions consider equality bonus. If we restrict to D heights, will the DP produce the optimal solution? Suppose an optimal solution uses a height h that is not in D but is between two xi values. As argued, we can adjust it to one of the nearest xi without increasing cost? But we need to ensure that the net profit does not decrease. Changing a building's height could affect equality with neighbors. If we change the height to a different value, it might break equality and lose bonus. However, if h is between two xi and we shift it to an endpoint xi, the equality with neighbors might be lost if neighbors also have that same h originally. But we can consider shifting the entire segment's common height to an endpoint of the interval that also gives the same sum of costs. If the segment's common height is in an interval where the sum of costs is constant, then shifting to an endpoint does not change cost and also does not break equality, because the entire segment is at the same value, and we can shift all buildings in the segment to the same endpoint, preserving equality. However, what if the segment's common height is exactly at some interior point that gives lower cost than any endpoint? But that cannot happen because the function is convex piecewise linear; the minimum value over a convex piecewise linear function is attained at some extreme point (a kink) or over an interval if there's a flat region. So interior points are not lower than endpoints of flat region. If it's a strict minimum at an interior point (i.e., slope changes from negative to positive exactly at a point that is not a kink), that would require the slope to be negative just left of that point and positive just right, but because slope changes only at x_i, the only way for sign change is at some x_i. So interior points cannot be strict minima; they are either on a flat region or have non-zero slope. So indeed minima occur at some x_i.
But what about a building that is not in a segment (i.e., its neighbors have different heights)? Its own optimal height to minimize its cost without caring about equality is its original xi. So we can set it to xi. So overall, we can restrict to heights from the set of distinct original xi.
Thus we can do DP over D candidate heights.
Now we need to compute C_i(h) for each building i and each candidate height h. Since D <= 2500, n <= 2500, we can precompute an n x D cost matrix: cost[i][j] = P * (h_j - x_i) if h_j >= x_i else M * (x_i - h_j). This is O(n*D) = 6.25M, fine.
Then DP: let dp[i][j] = minimum net cost (i.e., total modification cost minus bonuses earned so far) for first i buildings, with building i set to height h_j. Actually we want to maximize net profit = total bonus - total modification cost. But we can work with minimizing total cost - bonus, which is total modification cost - bonus. Then final answer = - min over j dp[n][j] (since net profit = - (min total cost - bonus)? Let's define: total cost (modification) = sum_i C_i(hi). total bonus = S * (# equal adjacent). net profit = total bonus - total modification cost. So we want to maximize (total bonus - total modification). Equivalent to minimize (total modification - total bonus). Let F = total modification - total bonus. Then net profit = -F. So we want to minimize F. So DP to compute min F.
We can compute dp[i][j] as the minimum value of (modification cost for first i buildings) - (bonuses from edges up to i-1) given that hi = h_j. Then recurrence:
dp[1][j] = C_1(h_j) (since no edges before building 1).
For i from 1 to n-1:
dp[i+1][k] = C_{i+1}(h_k) + min( dp[i][j] - S * 1(h_j == h_k) )? Actually we want to subtract bonus if equal. Since F = mod cost - bonus. So when we add building i+1 with height h_k, we add its modification cost C_{i+1}(h_k). Also we have an edge between i and i+1; if h_j == h_k, then we get a bonus S, meaning we subtract S from the total (since F = mod - bonus, bonus reduces F). So the contribution from the edge is -S if equal, else 0. So the recurrence is:
dp[i+1][k] = C_{i+1}(h_k) + min_{j} ( dp[i][j] + ( - S if h_j == h_k else 0 ) ).
That is: dp[i+1][k] = C_{i+1}(h_k) + min( dp[i][k] - S, min_{j != k} dp[i][j] ).
This matches earlier derived but with cost minus bonus.
So we need to compute for each i and each k, the value min( dp[i][k] - S, global min without k ). We can maintain for each i: global minimum m1 = min_j dp[i][j], and also the index idx where it occurs, and second minimum m2 = min_{j != idx} dp[i][j]. However, we need for each k, the value min_{j != k} dp[i][j]. That is:
if k != idx: then min_{j != k} = m1 (since m1 is at idx, and idx != k)
if k == idx: then min_{j != k} = m2
But careful if there are multiple indices achieving m1? Suppose the minimum is not unique; we need to handle that. In case of ties, if k is one of the indices that achieves the global minimum, but there exists another index also with same value, then min_{j != k} dp[i][j] could be equal to m1 as well (since another index gives same value). So the rule with m2 (second smallest distinct value) works only if we consider values not equal to dp[i][k]? Actually we need the minimum among all j != k. If there are multiple indices with the same minimum value, and k is one of them, then min_{j != k} could still be that same minimum value (from another j). So we need to know the minimum value among all j, and also the count of indices achieving that minimum. For each k, min_{j != k} = m1 if there exists at least one j != k with dp[i][j] = m1, else it's m2 (the next larger value). So we need to compute for each i: the minimum value m1, and the number of occurrences cnt_min. Then for each k:
if cnt_min > 1 or dp[i][k] != m1: then min_{j != k} = m1
else (cnt_min == 1 and dp[i][k] == m1): then min_{j != k} = m2
We can compute m2 as the minimum value among dp[i][j] that is greater than m1. If all values equal, then m2 = m1 but with cnt_min>1? Actually if all values equal, then cnt_min = D, then for any k, min_{j != k} = m1 because there is another j with same value. So we need m2 only when cnt_min == 1. So we can compute m1, cnt_min, and m2 as the minimum value among those not equal to m1 (or INF if none). This is easy to compute from the array.
So DP step: given dp_prev[j] for all j, compute for each k:
best_other = (dp_prev[k] == m1 and cnt_min == 1) ? m2 : m1
candidate = min( dp_prev[k] - S, best_other )
dp_next[k] = C_{i+1}(h_k) + candidate
This is O(D) per transition, total O(n*D).
Finally answer = - min_j dp[n][j] (since net profit = -F). But careful: net profit = total bonus - total modification. Our dp[n][j] gives total modification - total bonus? Let's confirm: Base dp[1][j] = C1(h_j). That's modification cost for building 1, no bonus. So dp[1][j] = mod1. For i=1 to 2: dp[2][k] = C2(h_k) + min( dp[1][k] - S, min_{j != k} dp[1][j] ). The term dp[1][k] - S includes the bonus S for edge (1,2) if heights equal. So dp[2][k] = mod1 + mod2 - (bonus if h1==h2). So yes, dp[i][j] = total modification of first i buildings minus total bonus from edges among them. So at the end, dp[n][j] = total modification - total bonus. So net profit = - dp[n][j] + (maybe some constant? Actually total profit = total bonus - total modification = - (total modification - total bonus) = - dp[n][j]. So maximizing net profit = minimizing dp[n][j]? Actually net profit = -dp[n][j]; so to maximize net profit, we want dp[n][j] as small as possible (more negative is larger profit). But dp[n][j] is nonnegative? Actually modification costs are nonnegative, and we subtract bonuses, so dp could become negative if bonuses exceed modification costs. So min dp[n][j] (most negative) gives max profit. But careful: The DP recurrence uses min over j, so dp values are computed as minima; so dp[n][j] will be the minimum possible total modification - total bonus for that ending height. Then overall optimum F = min_j dp[n][j]. Then net profit = -F. So answer = - min_j dp[n][j].
But wait: The DP recurrence computes dp[i+1][k] as minimum over previous j of dp[i][j] + cost transition. So dp[i][k] is the minimum total cost (mod - bonus) for prefix ending with height h_k. So indeed the overall optimum is min_k dp[n][k]. So answer = - (min_k dp[n][k]).
We need to output maximum net profit, which is an integer. So compute that.
Now we must verify with sample:
n=5, S=4, M=2, P=1. Heights: 1,2,1,5,4.
Candidate heights: distinct {1,2,5,4}? Actually 1,2,5,4 -> D=4.
Let's compute manually? Expected answer 9.
We'll test later.
Edge Cases: Need to be careful with large numbers: S, P, M up to 1e9, heights up to 1e6, so costs up to 1e9 * 1e6 = 1e15, but we can use 64-bit integers (long long). dp values could be negative if bonuses exceed costs, but that's fine.
Complexity: O(n*D) where D <= n = 2500 -> 6.25 million operations, each with a few arithmetic and comparisons, fine.
Memory: dp arrays of size D, we can keep two rows.
Implementation steps:
- Read n, S, M, P.
- Read array x of length n.
- Create sorted list of unique values: heights = sorted(set(x)). D = len(heights). But note: we must ensure that heights include all xi because optimal might use any of them. Also, do we need to consider other values? As argued, no. But let's double-check: Could an optimal solution use a height that is not in the set but yields same cost as some xi for a segment but maybe allows better transitions because of equality with neighbor that is not in the same segment? For example, building i is isolated, but we might change its height to some other value to match neighbor? That would be part of a segment if it matches neighbor. So then it would be in a segment. So the segment's common height is one of the xi in that segment as argued. So fine.
But what about a building that is part of two segments? That can't happen because it's a single height.
Thus we restrict to the set of distinct xi.
However, is it necessary to sort? The DP doesn't require ordering of candidate heights. But for computing cost_i(h) easily, we can just iterate over the list. Sorting not necessary but may help for something else? Not needed.
Now compute cost matrix: cost[i][j] = if heights[j] >= x_i then P*(heights[j] - x_i) else M*(x_i - heights[j]). Use 64-bit.
We'll have dp_prev array of length D, initialize with cost[0][j] for j=0..D-1.
For i from 1 to n-1 (0-indexed building indices):
- compute m1 = min(dp_prev), cnt_min, and m2 = INF (large). To compute m2, we can loop to find smallest value > m1. Or simpler: after obtaining m1, loop again to find the minimum value that is strictly greater than m1. If none, set m2 = INF (a very large number, but we will only use m2 when cnt_min == 1; if no such m2, then that means all values are equal and cnt_min = D >1, so m2 not needed). But if D=1? n >=2, but D could be 1 (all heights same). Then dp_prev has only one value. For transition, when there's only one candidate height, then for that height k, min_{j != k} does not exist. However, in DP recurrence, min_{j != k} is considered but if there is no j != k, then the only option when not equal is not available? Actually if D=1, then for building i+1, the transition only considers previous j = that same height. The min over j for dp[i+1][k] is dp[i][k] + C_{i+1}(k) - S? Because the only previous height is k. So we don't need min_{j != k}. Our formula using m1 and m2 would break because there is no other j. But we can treat that as a special case: if D==1, then dp_next[k] = C_{i+1}(k) + dp_prev[k] - S (since the only previous height is k, and equality gives bonus). But also we could consider that there is no alternative, so the recurrence reduces to dp_next[k] = C_{i+1}(k) + dp_prev[k] - S. That is consistent with min_{j} dp_prev[j] - S*I(j==k). Since only j=k, it's dp_prev[k] - S. So for D=1, we can just compute directly without need of m2. We'll handle D>=1. In practice D can be 1, we need to code accordingly. But we can still compute m1, cnt_min. If D==1, cnt_min=1, and there is no m2. Then for k (only one), best_other would be undefined. So we need to treat separately: if D == 1, then best_other doesn't exist, and min( dp_prev[k] - S, best_other ) is not defined. However, the min over j is just dp_prev[k] - S because there is no j != k. So we can just set dp_next[k] = C_{i+1}(k) + dp_prev[k] - S. So we'll handle D>1 normally, and if D==1, do special.
But D could be 1 only if all xi are equal. That's possible. So we must handle.
Now for D>1, we compute m1, cnt_min, and m2 (second smallest distinct value). Then for each k:
if cnt_min > 1 or dp_prev[k] != m1:
best_other = m1
else:
best_other = m2 (since dp_prev[k] == m1 and cnt_min == 1)
candidate = min(dp_prev[k] - S, best_other)
dp_next[k] = cost[i+1][k] + candidate
That's it.
At the end, compute min_dp = min(dp_prev) (after processing all buildings), answer = -min_dp.
Check with sample.
Let's compute manually with sample to ensure correctness.
n=5, S=4, M=2, P=1.
Heights: [1,2,1,5,4]
Distinct sorted: [1,2,4,5] but order not important. Let's assign indices: h0=1, h1=2, h2=4, h3=5.
Compute cost matrix:
Building 1 (x=1):
- h0=1: cost=0
- h1=2: since 2>=1, cost = P*(2-1)=1
- h2=4: P*(4-1)=3
- h3=5: P*(5-1)=4
Building 2 (x=2):
- h0=1: M*(2-1)=2
- h1=2: 0
- h2=4: P*(4-2)=2
- h3=5: P*(5-2)=3
Building 3 (x=1):
- h0=1:0
- h1=2:1
- h2=4:3
- h3=5:4
Building 4 (x=5):
- h0=1: M*(5-1)=8
- h1=2: M*(5-2)=6
- h2=4: M*(5-4)=2
- h3=5:0
Building 5 (x=4):
- h0=1: M*(4-1)=6
- h1=2: M*(4-2)=4
- h2=4:0
- h3=5: P*(5-4)=1
Now DP:
Initialize dp for i=0 (building 1): dp_prev = [0,1,3,4]
Now i=1 (building 2): compute m1=0, cnt_min? dp_prev[0]=0, others >0, so cnt_min=1, m2=1 (next smallest). Then for each k:
k=0 (h=1):
dp_prev[0]=0, cnt_min==1 and dp_prev[0]==m1 => best_other = m2 =1.
candidate = min(dp_prev[0]-S=0-4=-4, best_other=1) => min = -4.
dp_next[0] = cost[1][0] (for building2 height=1) = 2 + (-4) = -2.
k=1 (h=2):
dp_prev[1]=1, not equal to m1 (0) so best_other = m1 =0.
candidate = min(1-4=-3, 0) => min = -3? Actually min(-3,0) = -3.
dp_next[1] = cost[1][1] (for building2 height=2) = 0 + (-3) = -3.
k=2 (h=4):
dp_prev[2]=3, best_other=0.
candidate = min(3-4=-1, 0) = -1.
dp_next[2] = cost[1][2] = 2 + (-1) = 1.
k=3 (h=5):
dp_prev[3]=4, best_other=0.
candidate = min(4-4=0,0) = 0.
dp_next[3] = cost[1][3] = 3 + 0 = 3.
So dp after building2: [-2, -3, 1, 3]. Actually dp_next[1] = -3, dp_next[0] = -2, dp_next[2]=1, dp_next[3]=3.
Now i=2 (building 3, x=1): cost row: [0,1,3,4]
Compute m1 from dp_prev (now dp_prev = [-2,-3,1,3]) => min = -3 at index1, cnt_min=1, m2 = -2 (next smallest).
For each k:
k=0 (h=1):
dp_prev[0] = -2, not m1? m1=-3, so dp_prev[0] != m1, best_other = m1 = -3.
candidate = min(dp_prev[0]-S = -2-4=-6, best_other=-3) => min = -6.
dp_next[0] = cost[2][0]=0 + (-6) = -6.
k=1 (h=2):
dp_prev[1] = -3, this is m1 and cnt_min==1 => best_other = m2 = -2.
candidate = min(-3-4=-7, -2) => min = -7.
dp_next[1] = cost[2][1]=1 + (-7) = -6.
k=2 (h=4):
dp_prev[2]=1, best_other = m1 = -3.
candidate = min(1-4=-3, -3) => min = -3 (both -3).
dp_next[2] = cost[2][2]=3 + (-3) = 0.
k=3 (h=5):
dp_prev[3]=3, best_other = m1=-3.
candidate = min(3-4=-1, -3) = -3.
dp_next[3] = cost[2][3]=4 + (-3) = 1.
So dp after building3: [-6, -6, 0, 1].
Now i=3 (building 4, x=5): cost row: [8,6,2,0]
dp_prev = [-6,-6,0,1]. Compute m1 = -6, cnt_min: indices 0 and 1 both -6, so cnt_min=2. m2? For best_other when k is one of the mins, we need min_{j!=k}. Since cnt_min>1, for k that are -6, there is another j with -6, so best_other = m1 = -6. For k not -6, best_other = m1 = -6 as well (since m1 is -6 and there exists j != k with -6). So effectively best_other = -6 for all k. But we need to be careful: for k where dp_prev[k] = m1 and cnt_min>1, best_other = m1. For k where dp_prev[k] != m1, best_other = m1. So all get best_other = m1 = -6.
Now compute candidate for each k:
k=0 (h=1): dp_prev[0] = -6, best_other=-6.
candidate = min(-6 -4 = -10, -6) = -10? min(-10, -6) = -10.
dp_next[0] = cost[3][0]=8 + (-10) = -2.
k=1 (h=2): dp_prev[1] = -6, candidate = min(-10, -6) = -10? Actually -6-4=-10, min(-10, -6) = -10.
dp_next[1] = cost[3][1]=6 + (-10) = -4.
k=2 (h=4): dp_prev[2]=0, best_other=-6, candidate = min(0-4=-4, -6) = -6.
dp_next[2] = cost[3][2]=2 + (-6) = -4.
k=3 (h=5): dp_prev[3]=1, best_other=-6, candidate = min(1-4=-3, -6) = -6.
dp_next[3] = cost[3][3]=0 + (-6) = -6.
So dp after building4: [-2, -4, -4, -6].
Now i=4 (building 5, x=4): cost row: [6,4,0,1]
dp_prev = [-2,-4,-4,-6]. Compute m1 = -6 at index3, cnt_min=1 (only index3). m2 = -4? Actually next smallest after -6: we have -4 (indices 1,2) and -2. So m2 = -4.
Now for each k:
k=0 (h=1): dp_prev[0] = -2, not m1, best_other = m1 = -6.
candidate = min(-2-4=-6, -6) = -6 (both equal)
dp_next[0] = cost[4][0]=6 + (-6) = 0.
k=1 (h=2): dp_prev[1] = -4, not m1 (-6) so best_other = -6.
candidate = min(-4-4=-8, -6) = -8? Actually -8 < -6, so min = -8.
dp_next[1] = cost[4][1]=4 + (-8) = -4.
k=2 (h=4): dp_prev[2] = -4, not m1, best_other=-6.
candidate = min(-4-4=-8, -6) = -8.
dp_next[2] = cost[4][2]=0 + (-8) = -8.
k=3 (h=5): dp_prev[3] = -6, this is m1 and cnt_min==1 => best_other = m2 = -4.
candidate = min(-6-4=-10, -4) = -10.
dp_next[3] = cost[4][3]=1 + (-10) = -9.
So final dp = [0, -4, -8, -9]. Minimum = -9. Then net profit = - ( -9 ) = 9. That matches sample output.
Great.
Now we should consider if any nuance about the DP when S is large: dp values can become negative large, that's fine.
Now ensure we use 64-bit ints (long long in C++). Also need to handle INF for m2 when not existent; but for D>1, there will always be at least one other value, so m2 will exist (unless all dp values are equal, then cnt_min = D >1, so we never use m2). So we can compute m2 as INF initially, then loop to find the smallest value > m1. If none, set to some large number but we won't use it because cnt_min > 1.
Edge Cases:
- n up to 2500, D up to 2500, cost matrix of size 2500x2500 = 6.25M, which is okay ( ~50 MB if using long long 8 bytes? 6.25M * 8 = 50 MB, a bit high but still within typical memory limits (maybe 256 MB). Actually 6.25 million * 8 bytes = 50 million bytes = ~47.7 MB. Plus DP arrays etc. Might be okay but could be near limit. However, we can avoid storing full cost matrix by computing costs on the fly if needed, as we only need cost for current building each iteration. But we need cost for each building for each candidate height. We can precompute cost for each building and each candidate height in a vector of vectors. That's 6.25M entries; 47 MB might be okay in C++ (usually 256 MB), but Python might be problematic if we implement in Python? The problem expects a solution; we can write in C++ for performance. But the problem statement doesn't specify language; we can answer with algorithm. Since we are ChatGPT we should output final answer code in C++? The user asks: "Help Cat Noku determine the maximum possible net profit he can gain." That's a problem statement, but we need to provide solution. Usually we output a single integer. But the user wants us to "print a single integer". But they gave sample input and output. This is a coding problem. We need to produce code? The instruction: "Write a code to solve the problem." Possibly the user expects code. But as ChatGPT we can provide explanation and code.
Given the format, it's typical to provide solution in C++.
Thus we'll implement in C++.
Implementation details:
-
Read n, S, M, P.
-
Read vector x(n).
-
Compute distinct values: use set then vector h(d) sorted? Actually we need to map height to index. We'll sort distinct values for consistency, but ordering doesn't matter for DP as we treat indices.
-
D = h.size().
-
Precompute cost: vector<vector> cost(n, vector(D));
For i from 0 to n-1:
for j from 0 to D-1:
if (h[j] >= x[i]) cost[i][j] = (long long)P * (h[j] - x[i]);
else cost[i][j] = (long long)M * (x[i] - h[j]);
-
Initialize dp_prev = cost[0] (copy). Use vector dp_prev(D).
-
For i from 1 to n-1:
// compute m1, cnt_min, m2
long long m1 = *min_element(dp_prev.begin(), dp_prev.end()); // but we need index and count
Actually we need to compute m1, cnt_min, and m2 (second smallest distinct). We'll loop to compute.
long long m1 = dp_prev[0], m2 = LLONG_MAX;
int cnt_min = 0;
for (long long val : dp_prev) {
if (val < m1) { m1 = val; cnt_min = 1; } // but we need to update m2 properly. Better compute in two passes: first find m1 and cnt_min, then find m2.
}
Simpler:
long long m1 = dp_prev[0];
for (int j=1;j<D;++j) if (dp_prev[j] < m1) m1 = dp_prev[j];
cnt_min = 0;
for (int j=0;j<D;++j) if (dp_prev[j] == m1) cnt_min++;
long long m2 = LLONG_MAX;
for (int j=0;j<D;++j) if (dp_prev[j] > m1 && dp_prev[j] < m2) m2 = dp_prev[j];
// If cnt_min > 1, m2 not used.
// compute dp_next
vector dp_next(D);
for (int k=0;k<D;++k) {
long long best_other;
if (cnt_min > 1 || dp_prev[k] != m1) {
best_other = m1;
} else {
best_other = m2; // cnt_min == 1 and dp_prev[k] == m1
}
long long candidate = dp_prev[k] - S;
if (best_other < candidate) candidate = best_other; // min
dp_next[k] = cost[i][k] + candidate; // cost for building i (i index from 1 to n-1)
}
swap(dp_prev, dp_next);
-
After loop, long long minF = *min_element(dp_prev.begin(), dp_prev.end());
-
long long ans = -minF;
-
Print ans.
Check for D=1: In loop we compute m1, cnt_min=1, and m2 remains LLONG_MAX because no value > m1. But then for the only k, we go to else branch (cnt_min==1 and dp_prev[k]==m1) so best_other = m2 = LLONG_MAX. That's not correct. So we need to handle D=1 separately: if D==1, we can just compute directly without DP? Actually we can still apply DP but we need to treat transition specially. Simpler: For D==1, there's only one possible height, say h0. Then all buildings must have that height? But they can be changed to that height. The net profit is: we will have bonuses for all adjacent pairs if we set all to that height, but we could also choose not to have bonuses? But if all heights are the same, then all adjacent pairs are equal, so we get S*(n-1) bonus. However, we could also keep buildings at original heights, but they might not be all same. But we are forced to choose heights; we can set each building individually. But if only one candidate height, it's the only height we can choose, so each building will be that height. But wait, the set of candidate heights we restrict to is the distinct original xi. If D=1, all xi are the same. So the only height available is that value. Then indeed the optimal solution is to set all buildings to that height (since any other height is not allowed? But we argued we restrict to these heights; but could there be a better solution using a height not equal to that value? If all xi are equal, say all are 10. Then we can keep them at 10 (cost 0) and get bonus for all adjacent (since all equal). That yields profit = S*(n-1). Could any other height give higher profit? Changing any building to a different height would incur positive cost but could still get bonus if all equal? If we set all to some other h != 10, cost would be sum_i cost_i(h) = n * (if h >10: P*(h-10); if h<10: M*(10-h)). Since P and M positive, cost >0, and bonus still S*(n-1) if all equal. So profit would be S*(n-1) - positive cost, which is less. So optimum is keep original. So using only candidate height 10 is fine. So DP with D=1 should compute correctly: initial dp_prev = cost[0][0] = 0? Actually cost[0][0] = 0. Then for each next building i, we need dp_next[0] = cost[i][0] + min( dp_prev[0] - S, ... but there is no other j. So it should be dp_prev[0] - S. Our formula with best_other would be min(dp_prev[0] - S, best_other). But best_other doesn't exist, so we should treat it as only dp_prev[0] - S. So we need to handle D==1 specially: for each i, dp_next[0] = cost[i][0] + dp_prev[0] - S. That yields final dp = sum_i cost_i(h0) - S*(n-1). Since cost_i(h0) maybe 0 for all? Actually if h0 equals each xi, cost_i=0, so dp = -S*(n-1), profit = -dp = S*(n-1). Good.
Thus we can add a branch: if D==1, then simply compute total modification cost for all buildings to that height = sum_i cost_i(h0). Then net profit = S*(n-1) - total_cost. Since all adjacents equal. Actually if all heights are forced to same value, then all adjacent pairs are equal, so total bonus = S*(n-1). So answer = S*(n-1) - total_cost. That's simpler.
But we could also let DP run with special handling: for D==1, we can skip the m1,m2 logic and just compute dp_next[0] = cost[i][0] + dp_prev[0] - S. So either.
We'll implement the DP with D>1 logic; if D==1, handle separately.
Now confirm with another small case to ensure correctness.
But there is a nuance: Our DP recurrence considered the bonus as subtracting S when heights equal. However, we need to ensure that we don't double count or miss anything. Yes.
Now consider large values: dp values may become large negative (if S is large), but long long can hold up to about 9e18. Maximum absolute value: total modification cost could be up to n * max(|h - xi|) * max(P,M). xi up to 1e6, h up to 1e6, so difference up to 1e6, times n 2500 gives 2.5e9, times max(P,M) up to 1e9 gives 2.5e18. Bonus could be up to S*(n-1) up to 1e9*2500=2.5e12. So dp values magnitude up to ~1e18, which fits within 64-bit signed (9.22e18). So safe.
Now check for potential issues: The DP recurrence uses min( dp_prev[k] - S, best_other ). But what if best_other is INF? That would only happen when D=1, we handle separately.
Now confirm correctness of DP for general case. But is the DP correct given that we restrict heights to distinct xi? As argued, there exists optimal solution where each hi is one of the xi. However, is it possible that an optimal solution uses a height not in the set but yields the same dp value? In DP, we are exploring only those heights; if an optimal solution uses a height outside, we can map it to a height in the set without increasing cost? But we need to ensure that this mapping doesn't affect the equality bonuses. If we change a building's height to a different value, it could break equality with neighbors. So we can't arbitrarily change an individual building. However, we argued that we can transform an optimal solution into one where each segment's common height is an xi from that segment, and isolated buildings stay at their own xi. That transformation yields a solution with heights only from the set, and net profit not worse. So DP over that set will capture the optimum. So it's valid.
But we should double-check the segment argument more formally. Suppose we have an optimal solution with final heights h_i. Consider each connected component (maximal consecutive segment) where all buildings have the same height (maybe isolated building is a segment of length 1). For a segment of length L>=2, they all have same value H. The total contribution from that segment to the objective (net profit) is: S*(L-1) (since L-1 internal edges get bonus) minus sum_{i in segment} C_i(H). For a segment of length 1, there is no bonus, and its contribution is -C_i(H). For each segment, the value H is chosen to minimize sum_{i in segment} C_i(H) (since bonus is fixed given L and that they are equal). The minimization of sum_i C_i(H) is independent of other segments because edges between segments are not equal (by definition of segment boundaries, the heights are different, so no bonus). So for each segment, the optimal H is one that minimizes sum of costs over that segment. As argued, the minimizer can be chosen from the set of xi within that segment. So we can replace H with such an xi without increasing the segment's cost, and without affecting equality condition within the segment because all still equal. However, could changing H to a different value affect the equality with adjacent segments? At the boundaries, we have different heights by definition, so if we change the segment's common height, we must ensure it remains different from the neighbor's height. If the neighbor's height is also in the set, and we change H to some xi from the segment, it's possible that this new H equals the neighbor's height, merging segments and potentially gaining extra bonus. That would be even better