- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

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))

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

9

- Related Questions & Answers
- Program to find sum of rectangle whose sum at most k in Python
- Program to find maximum score from performing multiplication operations in Python
- Find Maximum number possible by doing at-most K swaps in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- 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
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to check final answer by performing given stack operations in Python
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Python Program to Create a class performing Calculator Operations
- Program to find minimum cost to reach final index with at most k steps in python
- Maximum sum subarray removing at most one element in C++
- Program to find minimum possible integer after at most k adjacent swaps on digits in Python
- Program to find maximum sum by flipping each row elements in Python

Advertisements