问题
We are given a sorted array.
Let the initial value of pass
be zero.
We can do the following operation any number of times:
Select any
k
numbers at a time. Add them all up. Add this sum topass
If a number, say
x
, is being selected for the first time from the array, then it is considered asx
only. When it is selected for the second time, then it is considered as-x
, and for the third time, again asx
, and so on...
For example, let the array be [-14, 10, 6, -6, -10, -10, -14]
and k = 4
, and we'll only do the operation once. We select these 4 numbers: {14, 10, 6, -6}
. Adding them up, we get 24
. Then, pass=pass+24
. Therefore, maximum value of pass is 24
.
How to obtain the maximum value of pass
?
回答1:
We can reformulate the problem as follows:
We have a list of numbers and we can activate or deactivate the numbers. We want to find the maximum sum of activated numbers, where in each pass we can switch exactly k
numbers.
For odd k
, we could do the following: Activate the maximum number (if it is positive) and use the remaining (k-1)
switches to switch any number twice, which will effectively leave the number in its previous state. Therefore, the maximum pass
value is the sum of positive numbers.
For even k
, this is slightly different since the number of activated numbers is always even. Therefore, we first find all positive numbers. Let the number of positive numbers be p
. If p
is even, then we are good and the sum of these numbers is the result. If p
is odd, we have to check two cases: Remove the smallest positive number or add the largest non-positive number. The maximum of these two cases is the result.
Edit from comments:
For the special case where k=n
, there are only two options: Either include all numbers or exclude all numbers. If the sum of numbers is greater than 0, this is the result. Otherwise, the result is 0.
来源:https://stackoverflow.com/questions/56527621/how-to-maximize-the-sum