Maximize sum after K negations | Practice | GeeksforGeeks

Given an array of integers of size N and a number K., Your must modify array arr[] exactly K number of times. Here modify array means in each operation you can replace any array element either arr[i] by -arr[i] or -arr[i] by arr[i]. You need to perform this operation in such a way that after K operations, the sum of the array must be maximum.

Example 1:
Input:
N = 5, K = 1
arr[] = {1, 2, -3, 4, 5}
Output:
15
Explanation:
We have k=1 so we can change -3 to 3 and
sum all the elements to produce 15 as output.
Example 2:
Input:
N = 10, K = 5
arr[] = {5, -2, 5, -4, 5, -12, 5, 5, 5, 20}
Output:
68
Explanation:
Here  we have k=5 so we turn -2, -4, -12 to
2, 4, and 12 respectively. Since we have
performed 3 operations so k is now 2. To get
maximum sum of array we can turn positive
turned 2 into negative and then positive
again so k is 0. Now sum is
5+5+4+5+12+5+5+5+20+2 = 68

Your Task:
You don't have to print anything, print ting is done by the driver code itself. You have to complete the function maximizeSum() which takes the array A[], its size N, and an integer K as inputs and returns the maximum possible sum.

Expected Time Complexity: O(N*logN)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N,K ≤ 105
-109 ≤ Ai ≤ 109
0
harshvardhansingh4581 day ago
A very simple java solution
class Solution {
   public static long maximizeSum(long a[], int n, int k)   {       long res = 0;       Arrays.sort(a);       for(int i=0;i<n;i++){           if(k> 0 && a[i] < 0){               a[i] = -1 * a[i];               k--;           }       }       Arrays.sort(a);       for(int i=1;i<=k;i++)           a[0] = -1 * a[0];       for(int i=0;i<n;i++)           res += a[i];       return res;   }}
0
nobugsanurag081 month ago
Time Complexity: O(N*logN) Auxiliary Space: O(1)
 
class Solution{   public:   long long int maximizeSum(long long int a[], int n, int k)   {       long long int sum=0;       sort(a,a+n);       long long int cntneg=0;       for(int i=0;i<n;i++){           if(a[i]>=0){               break;           }           else{               cntneg++;           }       }       if(cntneg<=k){           long long int ntop=0;           for(int i=0;i<n;i++){               if(ntop<cntneg){                   a[i]=a[i]*-1;                   ntop++;                   k--;               }               else{                   break;               }           }           sort(a,a+n);           if(k%2!=0){               a[0]=-1*a[0];           }       }       else{           long long int kp=0;           for(int i=0;i<n;i++){               if(kp<k){                   a[i]=a[i]*-1;                   kp++;               }           }       }       for(int i=0;i<n;i++){           sum+=a[i];       }       return sum;   }};
+2
sagrikasoni1 month ago
Java Solution

class Solution {

    public static long maximizeSum(long a[], int n, int k)
    {
        Arrays.sort(a);
       for(int i =0;i<n;i++){
           if(a[i]<0 && k>0){
               a[i] = -a[i];
               k--;
           }
       }
       long sum =0,min =Integer.MAX_VALUE;
       for(int i =0;i<n;i++){
           sum+=a[i];
           min = Math.min(min,a[i]);
       }
       
       if(k%2!=0) sum = sum-2*min;
     return sum;
    }
}
0
ashutoshrastogi2 months ago
Easy Java Soln
 
class Solution {

    public static long maximizeSum(long a[], int n, int k)
    {
        Arrays.sort(a);
        int i;
        long sum = 0;
        for(i=0;i<n;i++){
            if(a[i]<0 && k>0){
                k--;
                a[i] = Math.abs(a[i]);  
            }
            
            sum += a[i];
        }
        Arrays.sort(a);
        if(k==0)
            return sum;
        if(a[0]<0){
            sum-=a[0];
            if(k%2!=0)
                sum += Math.abs(a[0]);
            else
                sum += a[0];
        }
        else if(a[0]==0){
            return sum;    
        }
        else{
            sum-=a[0];
            if(k%2!=0)
                sum -= a[0];
            else
                sum += a[0];
        }
        
        return sum;
    }
}
0
waky2 months ago
//Simple Approach
long long int maximizeSum(long long int a[], int n, int k)
    {
        // Your code goes here
        sort(a,a+n);
        long long int mn = INT_MAX;
        long long int sum = 0;
        for(int i=0;i<n;i++){
            mn = min(mn,abs(a[i]));
            if(a[i]<0&&k){
                sum += -a[i];
                k--;
            }
            else
            sum += a[i];
        }
        if(k&1){
            return sum -= 2*mn;
        }
        return sum;
    }
0
ashisbehera3 months ago
simple java solution using greedy approach
   public static long maximizeSum(long a[], int n, int k)
    {
         // Your code goes here
        Arrays.sort(a);
        int neg = 0;
        for(int i=0;i<n;i++){//1st count how many -ve nos
            if(a[i] < 0)
                neg++;
        }
        int count =0;
        if(neg>0) {
            for (int i = 0; i < k && i < neg; i++) { // then make  //them +ve
                a[i] = a[i] * (-1);
                count++;
            }
        }
        if(count<k){//if still we have not reached kth iteration   //then make +ve to -ve
            k = k-count;
            Arrays.sort(a);
            int i=0;
            while(i<k){
                a[i] = a[i]*(-1);
                k--;
            }
        }
        int sum = 0;
        for(int j=0;j<n;j++){//finaly find sum
            sum+=a[j];
        }
        return sum;
    }
0
ghoshghoshbishal3 months ago
public static long maximizeSum(long a[], int n, int k)   {       Queue<Long> q = new PriorityQueue<>((i, j) -> (int)(i - j));       for(int i = 0; i < n; i++){           q.add(a[i]);       }       for(int i = 0; i < k; i++){           long temp = q.poll();           temp *= -1;           q.add(temp);       }              return q.stream().reduce((i, j) -> i + j).get();   }
+1
chessnoobdj4 months ago
C++
long long int maximizeSum(long long int a[], int n, int k)
    {
        int i = 0;
        sort(a, a+n);
        while(i<n && a[i] < 0 && k){
            a[i] *= -1;
            i += 1;
            k -= 1;
        }
        if(i<n && a[i] != 0 && k%2 != 0)
            a[i] *= -1;
        if(i == n && k%2 != 0)
            a[n-1] *= -1;
        return accumulate(a, a+n, 0);
    }
-1
manishmanimoney4 months ago
SIMPLE PYTHON CODE
class Solution:   def maximizeSum(self, a, n, k):       a=sorted(a)       i=0       count=0       while i<k and i<n:           if a[i]<0:               count+=1               a[i]*=-1               i+=1           else:               break       if (k-count)%2==0:           return(sum(a))       else:           a=sorted(a)           a[0]*=-1           return(sum(a))
+1
noob14prosometime4 months ago
Simple C++ Solution-
long long int maximizeSum(long long int a[], int n, int k)
    {
        // Your code goes here
        sort(a,a+n);
        int i=0;
        while(i<n){
            if(k>0){
                if(a[i]<0){
                    a[i]=-a[i];
                    k--;
                }
            }
            i++;
            
        }
        
        sort(a,a+n);
    
        while(k>0){
            a[0]=-a[0];
            k--;
        }
        long long int sum=0;
        for(int x=0;x<n;x++){
            sum+=a[x];
        }
        return sum;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.