Maximize Array sum by subtracting absolute of odd and adding absolute of even elements
Last Updated :
07 Jun, 2022
Given an array arr[] of size N, the task is to maximize the array sum by subtracting the absolute values of all odd and adding and absolute values of all even elements, with only at most one exceptional even-odd pair, i.e., only one even value can be subtracted and one odd element can be added.
Examples:
Input: arr[] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}
Output: 4
Explanation: Total absolute value subtracted = 5 + 3 + 1 + 1 + 3 + 5 = 18.
Total absolute value added = 4 + 2 + 0 + 2 + 4 = 12
Sum achieved = -6. Make {5, 0} the exceptional elements
Add 5 to sum and subtract 0 from sum.
So total value subtracted = 13 and total value added = 17
New Sum = 17 - 3 = 4. This is the maximum possible sum.
Input: arr[] = {1, -2, 3}
Output: 0
Approach: The problem can be solved based on the following idea:
To maximize the sum, the maximum absolute value which is subtracted (say max) and the minimum absolute value which is added (say min) should be the exceptional elements. So the sum will increase by 2*(max - min).
Now, this should be performed only when min is less than max. Otherwise, the above term will become negative and will reduce the total sum.
Follow the below steps to solve the problem:
- Initialize the variables Max, Min, Sum to store maximum absolute odd, minimum absolute even and total sum respectively.
- Traverse the array from 0 to N - 1.
- If element is odd then subtract its absolute value from the Sum and update Max.
- If element is even then add its absolute value to the Sum and update Min.
- If Min is greater than Max then no need to update sum.
- Else, update the Sum, Sum = Sum + 2*(Max - Min).
Below is the implementation of the above approach:
C++
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return maximum sum
// after swapping
int maxSum(int* arr, int N)
{
// Initialize the variables
int Max = INT_MIN;
int Min = INT_MAX;
int X, Sum = 0;
// Traverse the array
for (int i = 0; i < N; i++) {
X = arr[i];
// If element is odd then subtract
// it from the Sum and update maximum
if (X & 1) {
Max = max(Max, abs(X));
Sum -= abs(X);
}
// Else add it to the Sum and
// update minimum
else {
Min = min(Min, abs(X));
Sum += abs(X);
}
}
// If minimum even element is greater
// than maximum odd element then no
// need to swap
if (Min >= Max)
return Sum;
// Else print the sum after swapping
return (Sum + 2 * (Max - Min));
}
// Driver Code
int main()
{
int arr[] = { -5, -4, -3, -2, -1,
0, 1, 2, 3, 4, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << maxSum(arr, N);
return 0;
}
Java
// Java code for above approach
import java.io.*;
class GFG
{
// Function to return maximum sum
// after swapping
public static int maxSum(int arr[], int N)
{
// Initialize the variables
int Max = Integer.MIN_VALUE;
int Min = Integer.MAX_VALUE;
int X, Sum = 0;
// Traverse the array
for (int i = 0; i < N; i++) {
X = arr[i];
// If element is odd then subtract
// it from the Sum and update maximum
if ((X & 1) != 0) {
Max = Math.max(Max, Math.abs(X));
Sum -= Math.abs(X);
}
// Else add it to the Sum and
// update minimum
else {
Min = Math.min(Min, Math.abs(X));
Sum += Math.abs(X);
}
}
// If minimum even element is greater
// than maximum odd element then no
// need to swap
if (Min >= Max)
return Sum;
// Else print the sum after swapping
return (Sum + (2 * (Max - Min)));
}
public static void main(String[] args)
{
int arr[]
= { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };
int N = arr.length;
// Function call
System.out.print(maxSum(arr, N));
}
}
// This code is contributed by Rohit Pradhan.
Python3
# Python code to implement the approach
# Function to return maximum sum
# after swapping
import sys
def maxSum(arr, N):
# Initialize the variables
Max = -sys.maxsize -1
Min = sys.maxsize
X, Sum = 0,0
# Traverse the array
for i in range(N):
X = arr[i]
# If element is odd then subtract
# it from the Sum and update maximum
if (X & 1):
Max = max(Max, abs(X))
Sum -= abs(X)
# Else add it to the Sum and
# update minimum
else:
Min = min(Min, abs(X))
Sum += abs(X)
# If minimum even element is greater
# than maximum odd element then no
# need to swap
if (Min >= Max):
return Sum
# Else print the sum after swapping
return (Sum + 2 * (Max - Min))
# Driver Code
arr = [ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 ]
N = len(arr)
# Function call
print(maxSum(arr, N))
# This code is contributed by shinjanpatra
C#
// C# code for above approach
using System;
class GFG {
// Function to return maximum sum
// after swapping
static int maxSum(int[] arr, int N)
{
// Initialize the variables
int Max = Int32.MinValue;
int Min = Int32.MaxValue;
int X, Sum = 0;
// Traverse the array
for (int i = 0; i < N; i++) {
X = arr[i];
// If element is odd then subtract
// it from the Sum and update maximum
if ((X & 1) != 0) {
Max = Math.Max(Max, Math.Abs(X));
Sum -= Math.Abs(X);
}
// Else add it to the Sum and
// update minimum
else {
Min = Math.Min(Min, Math.Abs(X));
Sum += Math.Abs(X);
}
}
// If minimum even element is greater
// than maximum odd element then no
// need to swap
if (Min >= Max)
return Sum;
// Else print the sum after swapping
return (Sum + 2 * (Max - Min));
}
// Driver Code
public static void Main()
{
int[] arr
= { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };
int N = arr.Length;
// Function call
Console.Write(maxSum(arr, N));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript implementation of the approach
// Function to return maximum sum
// after swapping
function maxSum(arr,N)
{
// Initialize the variables
let Max = Number.MIN_VALUE;
let Min = Number.MAX_VALUE;
let X, Sum = 0;
// Traverse the array
for (let i = 0; i < N; i++) {
X = arr[i];
// If element is odd then subtract
// it from the Sum and update maximum
if (X & 1) {
Max = Math.max(Max, Math.abs(X));
Sum -= Math.abs(X);
}
// Else add it to the Sum and
// update minimum
else {
Min = Math.min(Min, Math.abs(X));
Sum += Math.abs(X);
}
}
// If minimum even element is greater
// than maximum odd element then no
// need to swap
if (Min >= Max)
return Sum;
// Else print the sum after swapping
return (Sum + 2 * (Max - Min));
}
// Driver Code
let arr = [ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 ];
let N = arr.length;
// Function call
document.write(maxSum(arr, N));
// This code is contributed by shinjanpatraa
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Maximize sum of an Array by flipping sign of all elements of a single subarray Given an array arr[] of N integers, the task is to find the maximum sum of the array that can be obtained by flipping signs of any subarray of the given array at most once. Examples: Input: arr[] = {-2, 3, -1, -4, -2} Output: 8Explanation: Flipping the signs of subarray {-1, -4, -2} modifies the arr
9 min read
Maximize array sum by alternating the signs of adjacent elements Given an array, arr[] of size N, the task is to find the maximum possible sum of array elements by alternating the signs of adjacent array elements. Examples: Input: arr[] = { -2, 1, 0 } Output: 3 Explanation: Alternating the signs of (arr[0], arr[1]) modifies arr[] to {2, -1, 0}. Alternating the si
7 min read
Minimize adding odd and subtracting even numbers to make all array elements equal to K Given an array, arr[] of size N and an integer K, the task is to find the minimum number of operations required to make all array elements equal to K by performing the following operations any number of times: Convert arr[i] to arr[i] + X, where X is an odd number.Convert arr[i] to arr[i] - Y, where
7 min read
Absolute Difference of even and odd indexed elements in an Array Given an array of integers arr, the task is to find the running absolute difference of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Out
6 min read
Maximize difference between sum of even and odd-indexed elements of a subsequence Given an array arr[] consisting of N positive integers, the task is to find the maximum possible difference between the sum of even and odd-indexed elements of a subsequence from the given array. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subseq
7 min read
Program to print Sum of even and odd elements in an array Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index position
13 min read
Minimize absolute Sum by subtracting one and two from adjacent indices Given an arr[] of length N, the task is to find the smallest possible sum of the array when we can subtract 1 and 2 respectively from two adjacent indices any number of times. Examples: Input: N = 1, arr[] = { -45 }Output: 45Explanation: As there are no consecutive indices present, Therefore, operat
8 min read
Maximum difference between sum of even and odd indexed elements of a Subarray Given an array nums[] of size N, the task is to find the maximum difference between the sum of even and odd indexed elements of a subarray. Examples: Input: nums[] = {1, 2, 3, 4, -5}Output: 9Explanation: If we select the subarray {4, -5} the sum of even indexed elements is 4 and odd indexed element
11 min read
Maximize difference between sum of even and odd-indexed elements of a subsequence | Set 2 Given an array arr[] consisting of N positive integers, the task is to find the maximum value of the difference between the sum of elements at even and odd indices for any subsequence of the array. Note: The value of N is always greater than 1. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9
11 min read
Maximize the count of adjacent element pairs with even sum by rearranging the Array Given an array, arr[] of N integers, the task is to find the maximum possible count of adjacent pairs with an even sum, rearranging the array arr[]. Examples: Input: arr[] = {5, 5, 1}Output: 2Explanation:The given array is already arranged to give the maximum count of adjacent pairs with an even sum
6 min read