
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Maximize Sum Of Array After K Negations in Python
Suppose we have an array A of integers, we have to modify the array in the following way −
We can choose an i and replace the A[i] with -A[i], and we will repeat this process K times. We have to return the largest possible sum of the array after changing it in this way.
So, if the array A = [4,2,3], and K = 1, then the output will be 5. So choose indices 1, the array will become [4,-2,3]
To solve this, we will follow these steps −
Sort the array A
for i in range 0 to length of A – 1
if A[i] <0, then A[i] := - A[i], and decrease k by 1
if k = 0, then break from the loop
if k is even, then
sp := A[0]
for i := 1 to length of A – 1
if A[i] > 0, then sp := minimum of sp and A[i]
return sum of the elements of A – (2*sp)
otherwise, return the sum of the elements of A
Example (Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def largestSumAfterKNegations(self, A, K): A.sort() for i in range(len(A)): if A[i] <0: A[i] = -A[i] K-=1 if K==0: break if K%2: smallest_positive = A[0] for i in range(1,len(A)): if A[i]>=0: smallest_positive = min(smallest_positive,A[i]) return sum(A) - (2*smallest_positive) else: return sum(A) ob1 = Solution() print(ob1.largestSumAfterKNegations([3,-1,0,2],3))
Input
[3,-1,0,2] 3
Output
6
- Related Articles
- Maximize array sum after K negation in C++
- Program to maximize the minimum value after increasing K sublists in Python
- Maximize the median of the given array after adding K elements to the same array in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Maximize the sum of array by multiplying prefix of array with -1 in C++
- Maximum array sum that can be obtained after exactly k changes in C++
- JavaScript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
- Program to maximize the number of equivalent pairs after swapping in Python
- Program to find maximize score after n operations in Python
- Maximize the subarray sum after multiplying all elements of any subarray with X in C++
- Maximize the maximum subarray sum after removing at most one element in C++
- Maximize the size of array by deleting exactly k sub-arrays to make array prime in C++
- Sum of Even Numbers After Queries in Python
- Maximize the sum of arr[i]*i in C++
- Two Sum Less Than K in Python
