Related Articles

Related Articles

Maximize array sum by alternating the signs of adjacent elements
  • Difficulty Level : Easy
  • Last Updated : 10 Dec, 2020

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:
Explanation: 
Alternating the signs of (arr[0], arr[1]) modifies arr[] to {2, -1, 0}. 
Alternating the signs of (arr[1], arr[2]) modifies arr[] to {2, 1, 0}. 
Therefore, the required output = (2 + 1 + 0) = 3, which is the maximum sum possible.

Input: arr[] = { 1, 1, -2, -4, 5 } 
Output: 13 
Explanation: 
Alternating the signs of (arr[2], arr[3]) modifies arr[] to { 1, 1, 2, 4, 5 } 
Therefore, the required output = (1 + 1 + 2 + 4 + 5) = 13, which is the maximum sum possible.

Approach: The problem can be solved using Greedy technique. The idea is based on the fact that the maximum count of negative elements in the array after alternating the signs of adjacent elements can’t be greater than 1. Follow the steps below to solve the problem:



  • Initialize a variable, say MaxAltSum, to store the maximum possible sum of array elements by alternating the signs of adjacent elements.
  • Traverse the array and count the number of negative elements in the array.
  • If count of negative elements in the array is even, then maximum possible sum possible by alternating the signs of adjacent array elements is equal to the sum of absolute value of array elements, i.e. MaxAltSum = Σabs(arr[i])
  • Otherwise, maximum possible sum obtained from the array by alternating the signs of adjacent array elements equal to the sum of the absolute value of all possible array elements, except the smallest absolute value of array elements. i.e, MaxAltSum = ((Σabs(arr[i])) – 2 * X), where X is the smallest absolute value of array elements.
  • Finally, print the value MaxAltSum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement 
// the above approach 
  
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to find the maximum sum by alternating 
// the signs of adjacent elements of the array 
int findMaxSumByAlternatingSign(int arr[], int N) 
    // Stores count of negative 
    // elements in the array 
    int cntNeg = 0; 
  
    // Stores maximum sum by alternating 
    // the signs of adjacent elements 
    int MaxAltSum = 0; 
  
    // Stores smallest absolute 
    // value of array elements 
    int SmValue = 0; 
  
    // Stores sum of absolute 
    // value of array elements 
    int sum = 0; 
  
    // Traverse the array 
    for (int i = 0; i < N; i++) { 
  
        // If arr[i] is 
        // a negative number 
        if (arr[i] < 0) { 
  
            // Update cntNeg 
            cntNeg += 1; 
        
  
        // Update sum 
        sum += abs(arr[i]); 
  
        // Update SmValue 
        SmValue = min(SmValue, 
                    abs(arr[i])); 
    
  
    // Update MaxAltSum 
    MaxAltSum = sum; 
  
    // If cntNeg is 
    // an odd number 
    if (cntNeg & 1) { 
  
        // Update MaxAltSum 
        MaxAltSum -= 2 * SmValue; 
    
    return MaxAltSum; 
  
// Drivers Code 
int main() 
  
    int arr[] = { 1, 1, -2, -4, 5 }; 
    int N = sizeof(arr) 
            / sizeof(arr[0]); 
  
    cout << findMaxSumByAlternatingSign( 
        arr, N); 

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement 
// the above approach 
import java.util.*;
  
class GFG{
  
// Function to find the maximum sum by alternating 
// the signs of adjacent elements of the array
static int findMaxSumByAlternatingSign(int arr[],
                                       int N) 
      
    // Stores count of negative 
    // elements in the array 
    int cntNeg = 0
  
    // Stores maximum sum by alternating 
    // the signs of adjacent elements 
    int MaxAltSum = 0
  
    // Stores smallest absolute 
    // value of array elements 
    int SmValue = 0
  
    // Stores sum of absolute 
    // value of array elements 
    int sum = 0
  
    // Traverse the array 
    for(int i = 0; i < N; i++)
    
          
        // If arr[i] is 
        // a negative number 
        if (arr[i] < 0
        
              
            // Update cntNeg 
            cntNeg += 1
        
          
        // Update sum 
        sum += Math.abs(arr[i]); 
          
        // Update SmValue 
        SmValue = Math.min(SmValue, 
                  Math.abs(arr[i])); 
    
  
    // Update MaxAltSum 
    MaxAltSum = sum; 
      
    // If cntNeg is 
    // an odd number 
    if (cntNeg % 2 == 1)
    
          
        // Update MaxAltSum 
        MaxAltSum -= 2 * SmValue; 
    
    return MaxAltSum; 
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 1, -2, -4, 5 }; 
    int N = arr.length; 
      
    System.out.print(findMaxSumByAlternatingSign( 
    arr, N)); 
}
}
  
// This code is contributed by jana_sayantan

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement 
# the above approach 
  
# Function to find the maximum sum by 
# alternating the signs of adjacent 
# elements of the array 
def findMaxSumByAlternatingSign(arr, N):
      
    # Stores count of negative 
    # elements in the array 
    cntNeg = 0 
  
    # Stores maximum sum by alternating 
    # the signs of adjacent elements 
    MaxAltSum = 0 
  
    # Stores smallest absolute 
    # value of array elements 
    SmValue = 0 
  
    # Stores sum of absolute 
    # value of array elements 
    sum = 0 
  
    # Traverse the array 
    for i in range(N):
          
        # If arr[i] is 
        # a negative number 
        if (arr[i] < 0):
              
            # Update cntNeg 
            cntNeg += 1
  
        # Update sum 
        sum += abs(arr[i]) 
  
        # Update SmValue 
        SmValue = min(SmValue, abs(arr[i]))
  
    # Update MaxAltSum 
    MaxAltSum = sum
  
    # If cntNeg is 
    # an odd number 
    if (cntNeg & 1):
          
        # Update MaxAltSum 
        MaxAltSum -= 2 * SmValue
          
    return MaxAltSum
  
# Driver Code 
if __name__ == '__main__':
      
    arr = [ 1, 1, -2, -4, 5
    N = len(arr) 
  
    print(findMaxSumByAlternatingSign(arr, N)) 
  
# This code is contributed by SURENDRA_GANGWAR

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement 
// the above approach 
using System;
  
class GFG{
  
// Function to find the maximum sum by alternating 
// the signs of adjacent elements of the array
static int findMaxSumByAlternatingSign(int []arr,
                                    int N) 
      
    // Stores count of negative 
    // elements in the array 
    int cntNeg = 0; 
  
    // Stores maximum sum by alternating 
    // the signs of adjacent elements 
    int MaxAltSum = 0; 
  
    // Stores smallest absolute 
    // value of array elements 
    int SmValue = 0; 
  
    // Stores sum of absolute 
    // value of array elements 
    int sum = 0; 
  
    // Traverse the array 
    for(int i = 0; i < N; i++)
    
          
        // If arr[i] is 
        // a negative number 
        if (arr[i] < 0) 
        
              
            // Update cntNeg 
            cntNeg += 1; 
        
          
        // Update sum 
        sum += Math.Abs(arr[i]); 
          
        // Update SmValue 
        SmValue = Math.Min(SmValue, 
                Math.Abs(arr[i])); 
    
  
    // Update MaxAltSum 
    MaxAltSum = sum; 
      
    // If cntNeg is 
    // an odd number 
    if (cntNeg % 2 == 1)
    
          
        // Update MaxAltSum 
        MaxAltSum -= 2 * SmValue; 
    
    return MaxAltSum; 
  
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 1, -2, -4, 5 }; 
    int N = arr.Length; 
      
    Console.Write(findMaxSumByAlternatingSign( 
    arr, N)); 
}
}
  
// This code is contributed by shivanisinghss2110

chevron_right


Output:

13

Time Complexity: O(N)
Auxiliary Space:O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :