- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Articles
- Program to find maximum score from performing multiplication operations in Python
- Program to find sum of rectangle whose sum at most k in Python
- Program to find expected sum of subarrays of a given array by performing some operations in Python
- Program to find maximum sum by removing K numbers from ends in python
- Program to find minimum possible maximum value after k operations in python
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Find Maximum number possible by doing at-most K swaps in C++
- Program to check final answer by performing given stack operations in Python
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Python Program to Create a class performing Calculator Operations
- C++ program to find maximum how many chocolates we can buy with at most k rupees
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Program to find maximum sum by flipping each row elements in Python