Program to find maximum sum by performing at most k negate operations in Python


Suppose we have a list of elements called nums we also have another value k. Now let us consider an operation where we select an element from nums and negate it. We can perform exactly k number of operations. We have to find the maximum resulting sum that can be generated.

So, if the input is like nums = [2, 1, -6, -2] k = 3, then the output will be 9, if we negate -6 and -2 and 1 shall get [2, -1, 6, 2] and its sum is 9.

To solve this, we will follow these steps −

  • n := size of nums

  • if n is same as 0, then

    • return 0

  • sort the list nums

  • for idx in range 0 to n - 1, do

    • if nums[idx] < 0 and k > 0, then

      • k := k - 1

      • nums[idx] := -nums[idx]

  • if k is odd, then

    • return (sum of all elements present in nums) - (2 * minimum of nums)

  • return sum of all elements present in nums

Example

Let us see the following implementation to get better understanding

def solve(nums, k):
   n = len(nums)
   if n == 0:
      return 0

   nums.sort()
   for idx in range(n):
      if nums[idx] < 0 and k > 0:
         k -= 1
         nums[idx] *= -1

   if k & 1 == 1:
      return sum(nums) - 2 * min(nums)

   return sum(nums)

nums = [2, 1, -6, -2]
k = 3
print(solve(nums, k))

Input

[2, 1, -6, -2], 3

Output

9

Updated on: 11-Oct-2021

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements