Open In App

Maximize array sum after K negations using Sorting

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of size n and a number k. We must modify array K a number of times. Here modify array means in each operation we can replace any array element arr[i] by -arr[i]. We need to perform this operation in such a way that after K operations, the sum of the array must be maximum?

Examples : 

Input : arr[] = {-2, 0, 5, -1, 2}, K = 4
Output: 10
Explanation:
1. Replace (-2) by -(-2), array becomes {2, 0, 5, -1, 2}
2. Replace (-1) by -(-1), array becomes {2, 0, 5, 1, 2}
3. Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}
4. Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}

Input : arr[] = {9, 8, 8, 5}, K = 3
Output: 20

Naive approach: This problem has a very simple solution, we just have to replace the minimum element arr[i] in the array by -arr[i] for the current operation. In this way, we can make sum of the array maximum after K operations. One interesting case is, that once the minimum element becomes 0, we don’t need to make any more changes. 

Implementation:

C++




// C++ program to maximize array sum after
// k operations.
#include <bits/stdc++.h>
using namespace std;
 
// This function does k operations on array in a way that
// maximize the array sum. index --> stores the index of
// current minimum element for j'th operation
int maximumSum(int arr[], int n, int k)
{
    // Modify array K number of times
    for (int i = 1; i <= k; i++) {
        int min = INT_MAX;
        int index = -1;
 
        // Find minimum element in array for current
        // operation and modify it i.e; arr[j] --> -arr[j]
        for (int j = 0; j < n; j++) {
            if (arr[j] < min) {
                min = arr[j];
                index = j;
            }
        }
 
        // this the condition if we find 0 as minimum
        // element, so it will useless to replace 0 by -(0)
        // for remaining operations
        if (min == 0)
            break;
 
        // Modify element of array
        arr[index] = -arr[index];
    }
 
    // Calculate sum of array
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { -2, 0, 5, -1, 2 };
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maximumSum(arr, n, k);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to maximize array sum after
// k operations.
#include<stdio.h>
#include<stdlib.h>
#include <limits.h>
 
// This function does k operations on array in a way that
// maximize the array sum. index --> stores the index of
// current minimum element for j'th operation
int maximumSum(int arr[], int n, int k)
{
    // Modify array K number of times
    for (int i = 1; i <= k; i++) {
        int min = INT_MAX;
        int index = -1;
 
        // Find minimum element in array for current
        // operation and modify it i.e; arr[j] --> -arr[j]
        for (int j = 0; j < n; j++) {
            if (arr[j] < min) {
                min = arr[j];
                index = j;
            }
        }
 
        // this the condition if we find 0 as minimum
        // element, so it will useless to replace 0 by -(0)
        // for remaining operations
        if (min == 0)
            break;
 
        // Modify element of array
        arr[index] = -arr[index];
    }
 
    // Calculate sum of array
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { -2, 0, 5, -1, 2 };
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d",maximumSum(arr, n, k));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to maximize array
// sum after k operations.
 
class GFG {
    // This function does k operations on array in a way
    // that maximize the array sum. index --> stores the
    // index of current minimum element for j'th operation
    static int maximumSum(int arr[], int n, int k)
    {
        // Modify array K number of times
        for (int i = 1; i <= k; i++) {
            int min = +2147483647;
            int index = -1;
 
            // Find minimum element in array for current
            // operation and modify it i.e; arr[j] --> -arr[j]
            for (int j = 0; j < n; j++) {
                if (arr[j] < min) {
                    min = arr[j];
                    index = j;
                }
            }
 
            // this the condition if we find 0 as minimum
            // element, so it will useless to replace 0 by
            // -(0) for remaining operations
            if (min == 0)
                break;
 
            // Modify element of array
            arr[index] = -arr[index];
        }
 
        // Calculate sum of array
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        return sum;
    }
 
    // Driver code
    public static void main(String arg[])
    {
        int arr[] = { -2, 0, 5, -1, 2 };
        int k = 4;
        int n = arr.length;
        System.out.print(maximumSum(arr, n, k));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 program to maximize
# array sum after k operations.
 
# This function does k operations on array
# in a way that maximize the array sum.
# index --> stores the index of current
# minimum element for j'th operation
 
 
def maximumSum(arr, n, k):
 
    # Modify array K number of times
    for i in range(1, k + 1):
 
        min = +2147483647
        index = -1
 
        # Find minimum element in array for
        # current operation and modify it
        # i.e; arr[j] --> -arr[j]
        for j in range(n):
 
            if (arr[j] < min):
 
                min = arr[j]
                index = j
 
        # this the condition if we find 0 as
        # minimum element, so it will useless to
        # replace 0 by -(0) for remaining operations
        if (min == 0):
            break
 
        # Modify element of array
        arr[index] = -arr[index]
 
    # Calculate sum of array
    sum = 0
    for i in range(n):
        sum += arr[i]
    return sum
 
 
# Driver code
arr = [-2, 0, 5, -1, 2]
k = 4
n = len(arr)
print(maximumSum(arr, n, k))
 
# This code is contributed by Anant Agarwal.


C#




// C# program to maximize array
// sum after k operations.
using System;
 
class GFG {
 
    // This function does k operations
    // on array in a way that maximize
    // the array sum. index --> stores
    // the index of current minimum
    // element for j'th operation
    static int maximumSum(int[] arr, int n, int k)
    {
 
        // Modify array K number of times
        for (int i = 1; i <= k; i++)
        {
            int min = +2147483647;
            int index = -1;
 
            // Find minimum element in array for
            // current operation and modify it
            // i.e; arr[j] --> -arr[j]
            for (int j = 0; j < n; j++)
            {
                if (arr[j] < min)
                {
                    min = arr[j];
                    index = j;
                }
            }
 
            // this the condition if we find
            // 0 as minimum element, so it
            // will useless to replace 0 by -(0)
            // for remaining operations
            if (min == 0)
                break;
 
            // Modify element of array
            arr[index] = -arr[index];
        }
 
        // Calculate sum of array
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { -2, 0, 5, -1, 2 };
        int k = 4;
        int n = arr.Length;
        Console.Write(maximumSum(arr, n, k));
    }
}
 
// This code is contributed by Nitin Mittal.


Javascript




<script>
     
// Javascript program to maximize array
// sum after k operations.
 
// This function does k operations
// on array in a way that maximize
// the array sum. index --> stores
// the index of current minimum
// element for j'th operation
function maximumSum(arr, n, k)
{
     
    // Modify array K number of times
    for(let i = 1; i <= k; i++)
    {
        let min = +2147483647;
        let index = -1;
 
        // Find minimum element in array for
        // current operation and modify it
        // i.e; arr[j] --> -arr[j]
        for(let j = 0; j < n; j++)
        {
            if (arr[j] < min)
            {
                min = arr[j];
                index = j;
            }
        }
 
        // This the condition if we find 0 as
        // minimum element, so it will useless to
        // replace 0 by -(0) for remaining operations
        if (min == 0)
            break;
 
        // Modify element of array
        arr[index] = -arr[index];
    }
 
    // Calculate sum of array
    let sum = 0;
    for(let i = 0; i < n; i++)
        sum += arr[i];
         
    return sum;
}
     
// Driver code
let arr = [ -2, 0, 5, -1, 2 ];
let k = 4;
let n = arr.length;
 
document.write(maximumSum(arr, n, k));
 
// This code is contributed by code_hunt
 
</script>


PHP




<?php
// PHP program to maximize
// array sum after k operations.
 
// This function does k operations
// on array in a way that maximize
// the array sum. index --> stores
// the index of current minimum
// element for j'th operation
function maximumSum($arr, $n, $k)
{
    $INT_MAX = 0;
    // Modify array K
    // number of times
    for ($i = 1; $i <= $k; $i++)
    {
        $min = $INT_MAX;
        $index = -1;
 
        // Find minimum element in
        // array for current operation
        // and modify it i.e;
        // arr[j] --> -arr[j]
        for ($j = 0; $j < $n; $j++)
        {
            if ($arr[$j] < $min)
            {
                $min = $arr[$j];
                $index = $j;
            }
        }
 
        // this the condition if we
        // find 0 as minimum element, so
        // it will useless to replace 0
        // by -(0) for remaining operations
        if ($min == 0)
            break;
 
        // Modify element of array
        $arr[$index] = -$arr[$index];
    }
 
    // Calculate sum of array
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
        $sum += $arr[$i];
    return $sum;
}
 
// Driver Code
$arr = array(-2, 0, 5, -1, 2);
$k = 4;
$n = sizeof($arr) / sizeof($arr[0]);
echo maximumSum($arr, $n, $k);
     
// This code is contributed
// by nitin mittal.
?>


Output

10

Time Complexity: O(k*n) 
Auxiliary Space: O(1)

Approach 2 (Using Sort):  When there is a need to negate at most k elements.

Follow the steps below to solve this problem:

  1. Sort the given array arr.
  2. Then for a given value of k, Iterate through the array till k remains greater than 0, If the value of the array at any index is less than 0 we will change its sign and decrement k by 1.
  3. If we find a 0 in the array we will immediately set k equal to 0 to maximize our result.
  4. In some cases, if we have all the values in an array greater than 0 we will change the sign of positive values, as our array is already sorted we will be changing signs of lower values present in the array which will eventually maximize our sum.

Below is the implementation of the above approach:

C++




// C++ program to find maximum array sum after at most k
// negations.
#include <bits/stdc++.h>
 
using namespace std;
 
int sol(int arr[], int n, int k)
{
    int sum = 0;
    int i = 0;
 
    // Sorting given array using in-built sort function
    sort(arr, arr + n);
    while (k > 0) {
        // If we find a 0 in our sorted array, we stop
        if (arr[i] >= 0)
            break;
        else {
            arr[i] = (-1) * arr[i];
            k = k - 1;
        }
        i++;
    }
 
    // Calculating sum
  int minpos=INT_MAX;
    for (int j = 0; j < n; j++)
    {
      if(arr[j]>=0)
      minpos=min(minpos,arr[j]);
        sum += arr[j];
    }
  if(minpos==0 || k%2==0)
    return sum;
  return (sum-2*minpos);
}
 
// Driver code
int main()
{
    int arr[] = {-2, 0, 5, -1, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << sol(arr, n, 4) << endl;
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C++ program to find maximum array sum after at most k
// negations.
#include <stdio.h>
#include <stdlib.h>
 
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
 
int sol(int arr[], int n, int k)
{
    int sum = 0;
    int i = 0;
 
    // Sorting given array using in-built sort function
    qsort(arr, n, sizeof(int), cmpfunc);
    while (k > 0) {
        // If we find a 0 in our sorted array, we stop
        if (arr[i] >= 0)
            k = 0;
        else {
            arr[i] = (-1) * arr[i];
            k = k - 1;
        }
        i++;
    }
 
    // Calculating sum
    for (int j = 0; j < n; j++)
        sum += arr[j];
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { -2, 0, 5, -1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d", sol(arr, n, 4));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to find maximum array sum
// after at most k negations.
import java.util.Arrays;
 
public class GFG {
 
    static int sol(int arr[], int k)
    {
        // Sorting given array using in-built java sort
        // function
        Arrays.sort(arr);
        int sum = 0;
 
        int i = 0;
        while (k > 0) {
            // If we find a 0 in our sorted array, we stop
            if (arr[i] >= 0)
                k = 0;
            else {
                arr[i] = (-1) * arr[i];
                k = k - 1;
            }
            i++;
        }
 
        // Calculating sum
        for (int j = 0; j < arr.length; j++)
            sum += arr[j];
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { -2, 0, 5, -1, 2 };
        System.out.println(sol(arr, 4));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 program to find maximum array
# sum after at most k negations
 
 
def sol(arr, k):
 
    # Sorting given array using
    # in-built java sort function
    arr.sort()
 
    Sum = 0
    i = 0
 
    while (k > 0):
 
        # If we find a 0 in our
        # sorted array, we stop
        if (arr[i] >= 0):
            k = 0
        else:
            arr[i] = (-1) * arr[i]
            k = k - 1
 
        i += 1
 
    # Calculating sum
    for j in range(len(arr)):
        Sum += arr[j]
 
    return Sum
 
 
# Driver code
arr = [-2, 0, 5, -1, 2]
 
print(sol(arr, 4))
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program to find maximum array sum
// after at most k negations.
using System;
  
class GFG{
  
static int sol(int []arr, int k)
{
     
    // Sorting given array using
    // in-built java sort function
    Array.Sort(arr);
     
    int sum = 0;
    int i = 0;
     
    while (k > 0)
    {
         
        // If we find a 0 in our
        // sorted array, we stop
        if (arr[i] >= 0)
            k = 0;
 
        else
        {
            arr[i] = (-1) * arr[i];
            k = k - 1;
        }
        i++;
    }
     
    // Calculating sum
    for(int j = 0; j < arr.Length; j++)
    {
        sum += arr[j];
    }
    return sum;
}
 
// Driver code
public static void Main(string[] args)
{
    int []arr = { -2, 0, 5, -1, 2 };
     
    Console.Write(sol(arr, 4));
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// JavaScript program to find maximum array sum
// after at most k negations.
 
    function sol(arr, k)
    {
     
        // Sorting given array using in-built
        // java sort function
        arr.sort();
        let sum = 0;
  
        let i = 0;
        while (k > 0)
        {
         
            // If we find a 0 in our
            // sorted array, we stop
            if (arr[i] >= 0)
                k = 0;
  
            else
            {
                arr[i] = (-1) * arr[i];
                k = k - 1;
            }
  
            i++;
        }
  
        // Calculating sum
        for (let j = 0; j < arr.length; j++)
        {
            sum += arr[j];
        }
        return sum;
    }
 
// Driver code
    let arr = [ -2, 0, 5, -1, 2 ];
    document.write(sol(arr, 4));
 
// This code is contributed by souravghosh0416.                            
</script>


Output

10

Time Complexity: O(n*logn) 
Auxiliary Space: O(1)

Approach 3(Using Sort):

The above approach 2 is optimal when there is a need to negate at most k elements. To solve when there are exactly k negations the algorithm is given below.

  1. Sort the array in ascending order. Initialize i = 0.
  2. Increment i and multiply all negative elements by -1 till k becomes or a positive element is reached.
  3. Check if the end of the array has occurred. If true then go to (n-1)th element.
  4. If k ==0 or k is even, return the sum of all elements. Else multiply the absolute of minimum of ith or (i-1) th element by -1.
  5. Return sum of the array.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate sum of the array
long long int sumArray(long long int* arr, int n)
{
    long long int sum = 0;
 
    // Iterate from 0 to n - 1
    for (int i = 0; i < n; i++)
        sum += arr[i];
    return sum;
}
 
// Function to maximize sum
long long int maximizeSum(long long int arr[], int n, int k)
{
    sort(arr, arr + n);
    int i = 0;
 
    // Iterate from 0 to n - 1
    for (i = 0; i < n; i++) {
        if (k && arr[i] < 0) {
            arr[i] *= -1;
            k--;
            continue;
        }
        break;
    }
    if (i == n)
        i--;
    if (k == 0 || k % 2 == 0)
        return sumArray(arr, n);
    if (i != 0 && abs(arr[i]) >= abs(arr[i - 1]))
        i--;
    arr[i] *= -1;
    return sumArray(arr, n);
}
 
// Driver Code
int main()
{
    int n = 5;
    int k = 4;
    long long int arr[5] = { -2, 0, 5, -1, 2 };
    // Function Call
    cout << maximizeSum(arr, n, k) << endl;
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program for the above approach
#include <stdio.h>
#include<stdlib.h>
 
// Function to calculate sum of the array
long long int sumArray(long long int* arr, int n)
{
    long long int sum = 0;
 
    // Iterate from 0 to n - 1
    for (int i = 0; i < n; i++)
        sum += arr[i];
    return sum;
}
 
void merge(long long int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
  
    /* create temp arrays */
    int L[n1], R[n2];
  
    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
  
    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        }
        else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
  
    /* Copy the remaining elements of L[], if there
    are any */
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
  
    /* Copy the remaining elements of R[], if there
    are any */
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}
  
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(long long int arr[], int l, int r)
{
    if (l < r) {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        int m = l + (r - l) / 2;
  
        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
  
        merge(arr, l, m, r);
    }
}
 
// Function to maximize sum
long long int maximizeSum(long long int arr[], int n, int k)
{
    mergeSort(arr,0,n-1);
    int i = 0;
 
    // Iterate from 0 to n - 1
    for (i = 0; i < n; i++) {
        if (k && arr[i] < 0) {
            arr[i] *= -1;
            k--;
            continue;
        }
        break;
    }
    if (i == n)
        i--;
    if (k == 0 || k % 2 == 0)
        return sumArray(arr, n);
    if (i != 0 && abs(arr[i]) >= abs(arr[i - 1]))
        i--;
    arr[i] *= -1;
    return sumArray(arr, n);
}
 
// Driver Code
int main()
{
    int n = 5;
    int k = 4;
    long long int arr[] = { -2, 0, 5, -1, 2 };
    // Function Call
    printf("%lld",maximizeSum(arr,n,k));
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to calculate sum of the array
    static int sumArray(int[] arr, int n)
    {
        int sum = 0;
        // Iterate from 0 to n - 1
        for (int i = 0; i < n; i++)
            sum += arr[i];
        return sum;
    }
 
    // Function to maximize sum
    static int maximizeSum(int arr[], int n, int k)
    {
        Arrays.sort(arr);
        int i = 0;
 
        // Iterate from 0 to n - 1
        for (i = 0; i < n; i++) {
            if (k != 0 && arr[i] < 0) {
                arr[i] *= -1;
                k--;
                continue;
            }
            break;
        }
        if (i == n)
            i--;
 
        if (k == 0 || k % 2 == 0)
            return sumArray(arr, n);
 
        if (i != 0 && Math.abs(arr[i]) >= Math.abs(arr[i - 1]))
            i--;
 
        arr[i] *= -1;
        return sumArray(arr, n);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int n = 5;
        int arr[] = { -2, 0, 5, -1, 2 };
        int k = 4;
        // Function Call
        System.out.print(maximizeSum(arr, n, k));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 program for the above approach
 
# Function to calculate sum of the array
def sumArray(arr, n):
    sum = 0
     
    # Iterate from 0 to n - 1
    for i in range(n):
        sum += arr[i]
         
    return sum
 
# Function to maximize sum
def maximizeSum(arr, n, k):
     
    arr.sort()
    i = 0
   
    # Iterate from 0 to n - 1
    for i in range(n):
        if (k and arr[i] < 0):
            arr[i] *= -1
            k -= 1
            continue
         
        break
     
    if (i == n):
        i -= 1
 
    if (k == 0 or k % 2 == 0):
        return sumArray(arr, n)
 
    if (i != 0 and abs(arr[i]) >= abs(arr[i - 1])):
        i -= 1
 
    arr[i] *= -1
    return sumArray(arr, n)
 
# Driver Code
n = 5
k = 4
arr = [ -2, 0, 5, -1, 2 ]
   
# Function Call
print(maximizeSum(arr, n, k))
 
# This code is contributed by rohitsingh07052


C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate sum of the array
static int sumArray( int[] arr, int n)
{
    int sum = 0;
    
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
        sum += arr[i];
    }
    return sum;
}
  
// Function to maximize sum
static int maximizeSum(int[] arr, int n, int k)
{
    Array.Sort(arr);
    int i = 0;
    
    // Iterate from 0 to n - 1
    for(i = 0; i < n; i++)
    {
        if (k != 0 && arr[i] < 0)
        {
            arr[i] *= -1;
            k--;
            continue;
        }
        break;
    }
    if (i == n)
        i--;
  
    if (k == 0 || k % 2 == 0)
    {
        return sumArray(arr, n);
    }
  
    if (i != 0 && Math.Abs(arr[i]) >=
                  Math.Abs(arr[i - 1]))
    {
        i--;
    }
  
    arr[i] *= -1;
    return sumArray(arr, n);
}
 
// Driver Code
static public void Main()
{
    int n = 5;
    int[] arr = { -2, 0, 5, -1, 2 };
    int k = 4;
    
    // Function Call
    Console.Write(maximizeSum(arr, n, k));
}
}
 
// This code is contributed by shubhamsingh10


Javascript




<script>
// Javascript program for the above approach
 
// Function to calculate sum of the array
function  sumArray(arr,n)
{
    let sum = 0;
     
    // Iterate from 0 to n - 1
    for(let i = 0; i < n; i++)
    {
        sum += arr[i];
    }
    return sum;
}
 
// Function to maximize sum
function maximizeSum(arr,n,k)
{
    (arr).sort(function(a,b){return a-b;});
    let i = 0;
     
    // Iterate from 0 to n - 1
    for(i = 0; i < n; i++)
    {
        if (k != 0 && arr[i] < 0)
        {
            arr[i] *= -1;
            k--;
            continue;
        }
        break;
    }
    if (i == n)
        i--;
   
    if (k == 0 || k % 2 == 0)
    {
        return sumArray(arr, n);
    }
   
    if (i != 0 && Math.abs(arr[i]) >=
        Math.abs(arr[i - 1]))
    {
        i--;
    }
   
    arr[i] *= -1;
    return sumArray(arr, n);
}
 
// Driver Code
let n = 5;
let k = 4;   
let arr=[ -2, 0, 5, -1, 2 ];
 
// Function Call
document.write(maximizeSum(arr, n, k));
 
// This code is contributed by ab2127
</script>


Output

10

Time Complexity: O(n*logn)  
Auxiliary Space: O(1)

Maximize array sum after K negations | Set 2 

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Previous Article
Next Article

Similar Reads

Maximize array sum after K negations using Priority Queue
Given an array of size n and a number k. We must modify array K number of times. Here modify array means in each operation we can replace any array element arr[i] by -arr[i]. We need to perform this operation in such a way that after K operations, sum of array must be maximum? Examples: Input : arr[] = {-2, 0, 5, -1, 2} K = 4 Output: 10 // Replace
5 min read
Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2
Given an array arr[] consisting of N strings, the task is to sort the array in ascending order after modifying each string by removing all characters that are not perfect power of 2 and then sort the modified string in decreasing order. Examples: Input: arr[] = {"aaacbb", "geeks", "aaa"}Output: cbb skgeeExplanation:Following are the modified string
10 min read
Sorting objects using In-Place sorting algorithm
Given an array of red, blue and yellow objects, the task is to use an in-place sorting algorithm to sort the array in such a way that all the blue objects appear before all the red objects and all the red objects appear before all the yellow objects.Examples: Input: arr[] = {"blue", "red", "yellow", "blue", "yellow"} Output: blue blue red yellow ye
7 min read
Maximize sum of remaining elements after every removal of the array half with greater sum
Given an array arr[] consisting of N integers, the task is to maximize the resultant sum obtained after adding remaining elements after every removal of the array half with maximum sum. Array can be divided into two non-empty halves left[] and right[] where left[] contains the elements from the indices [0, N/2) and right[] contains the elements fro
22 min read
Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
13 min read
C++ Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Java Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Python3 Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Maximize Array sum after incrementing at most K elements followed by dividing array by X
Given an array, arr[] and two integers, K and X, the task is to maximize the sum of the array elements after at most K increments of any elements, then dividing all of the elements by X Example: Input: arr = {16, 15, 17}, K = 8, X = 10Output: 5Explanation: At most 8 increments are allowed. So, increment element at index 0 by 4 and element at index
8 min read
Article Tags :
Practice Tags :