How to maximize the sum?

2020-02-26 14:05发布

We are given a sorted array.

Let the initial value of pass be zero.

We can do the following operation any number of times:

  1. Select any k numbers at a time. Add them all up. Add this sum to pass

  2. If a number, say x, is being selected for the first time from the array, then it is considered as x only. When it is selected for the second time, then it is considered as -x , and for the third time, again as x, 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条回答
Summer. ? 凉城
2楼-- · 2020-02-26 14:30

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.

查看更多
登录 后发表回答