Maximum Sum of Products of two arrays by toggling adjacent bits

Given an integer array arr1 and a binary array arr2 of same size, the task is to find the maximum possible sum of products of these arrays, i.e. (arr1[0] * arr2[0]) + (arr1[1] * arr2[1]) + ….. (arr1[N-1] * arr2[N-1]) obtained by toggling any 2 adjacent bits in the array arr2. This toggle can be done infinite number of times.
Toggling of 2 adjacent bits in array arr2 is done as follows:
Â
- 00 is toggled to 11
- 01 is toggled to 10
- 10 is toggled to 01
- 11 is toggled to 00
Examples:Â
Â
Input: arr1 = {2, 3, 1}, arr2 = {0, 0, 1}
Output: 6
Explanation:
if we put 1 corresponding to a positive integer
then arr2 will be {1, 1, 1}
No. of 1's initially and now are odd
It means parity is same
so this arrangement is fine
Hence sum will be 2 + 3 + 1 = 6.
Input: arr1 = {2, -4, 5, 3}, arr2 = {0, 1, 0, 1}
Output: 8
Â
Approach :
Â
- After every operation parity remains the same, i.e. no. of 1’s is even if initially it is even, or odd if initially it is odd.
- The second observation is that to toggling of i’th and j’th bit can be done by toggling from i’th bit like (i, i+1), (i+1, i+2) …. (j-1, j) here every bit is toggling twice (if bit is toggle twice then its come to its initial value) except i and j then ultimately i’th and j’th bits toggle.
- From these two observations, it can be shown that we can make any arrangement of 1’s and 0’s in array arr2. The only thing we need to take care of is the parity of ones and zeroes. The final parity must be the same as of initial parity.
- To get the maximum sum put 1 at the i’th position of arr2 if the element at the i’th position in arr1 is positive else put 0.
Below is the implementation of the above approach:Â
Â
C++
// C++ program to find the maximum SoP of two arrays// by toggling adjacent bits in the second arrayÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to return Max Sumint maxSum(int arr1[], int arr2[], int n){Â Â Â Â // intialParity and finalParity are 0Â Â Â Â // if total no. of 1's is even else 1Â Â Â Â int initialParity = 0, finalParity = 0;Â
    // minPositive and maxNegative will store    // smallest positive and smallest negative    // integer respectively.    int sum = 0,        minPositive = INT_MAX,        maxNegative = INT_MIN;Â
    for (int i = 0; i < n; i++) {Â
        // Count of Initial Parity        initialParity += arr2[i];Â
        // if arr1[i] is positive then add 1        // in finalParity to get 1 at arr2[i]        if (arr1[i] >= 0) {Â
            finalParity += 1;            sum += arr1[i];            minPositive = min(minPositive, arr1[i]);        }        else {            maxNegative = max(maxNegative, arr1[i]);        }    }Â
    // if both parity are odd or even    // then return sum    if (initialParity % 2 == finalParity % 2) {        return sum;    }Â
    // else add one more 1 or remove 1    else {Â
        // if minPositive > maxNegative,        // put 1 at maxNegative        // and add it to our sum        if (minPositive + maxNegative >= 0) {Â
            return sum + maxNegative;        }Â
        // else remove minPositive no.        else {Â
            return sum - minPositive;        }    }}Â
// Driver codeint main(){Â Â Â Â int arr1[] = { 2, -4, 5, 3 };Â Â Â Â int arr2[] = { 0, 1, 0, 1 };Â
    int n = sizeof(arr1) / sizeof(arr1[0]);    cout << maxSum(arr1, arr2, n) << endl;Â
    return 0;} |
Java
// Java program to find the maximum SoP // of two arrays by toggling adjacent bits // in the second arrayclass GFG{Â
// Function to return Max Sumstatic int maxSum(int arr1[], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int arr2[], int n){Â Â Â Â // intialParity and finalParity are 0Â Â Â Â // if total no. of 1's is even else 1Â Â Â Â int initialParity = 0, finalParity = 0;Â
    // minPositive and maxNegative will store    // smallest positive and smallest negative    // integer respectively.    int sum = 0,        minPositive = Integer.MAX_VALUE,        maxNegative = Integer.MIN_VALUE;Â
    for (int i = 0; i < n; i++)    {Â
        // Count of Initial Parity        initialParity += arr2[i];Â
        // if arr1[i] is positive then add 1        // in finalParity to get 1 at arr2[i]        if (arr1[i] >= 0)        {Â
            finalParity += 1;            sum += arr1[i];            minPositive = Math.min(minPositive,                                       arr1[i]);        }        else        {            maxNegative = Math.max(maxNegative,                                       arr1[i]);        }    }Â
    // if both parity are odd or even    // then return sum    if (initialParity % 2 == finalParity % 2)    {        return sum;    }Â
    // else add one more 1 or remove 1    else    {Â
        // if minPositive > maxNegative,        // put 1 at maxNegative        // and add it to our sum        if (minPositive + maxNegative >= 0)        {            return sum + maxNegative;        }Â
        // else remove minPositive no.        else        {            return sum - minPositive;        }    }}Â
// Driver codepublic static void main(String []args){Â Â Â Â int arr1[] = { 2, -4, 5, 3 };Â Â Â Â int arr2[] = { 0, 1, 0, 1 };Â
    int n = arr1.length;    System.out.println(maxSum(arr1, arr2, n));}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program to find the # maximum SoP of two arrays by # toggling adjacent bits## in the second arrayimport sysÂ
# Function to return Max Sumdef maxSum(arr1, arr2, n) :Â
    # intialParity and finalParity are 0    # if total no. of 1's is even else 1    initialParity, finalParity = 0, 0Â
    # minPositive and maxNegative will store    # smallest positive and smallest negative    # integer respectively.    sum = 0    minPositive = sys.maxsize    maxNegative = -sys.maxsize - 1Â
    for i in range(n) :Â
        # Count of Initial Parity        initialParity += arr2[i];Â
        # if arr1[i] is positive then add 1        # in finalParity to get 1 at arr2[i]        if (arr1[i] >= 0) :Â
            finalParity += 1            sum += arr1[i]            minPositive = min(minPositive, arr1[i])Â
        else :            maxNegative = max(maxNegative, arr1[i])             # if both parity are odd or even    # then return sum    if (initialParity % 2 == finalParity % 2) :        return sumÂ
    # else add one more 1 or remove 1    else :Â
        # if minPositive > maxNegative,        # put 1 at maxNegative        # and add it to our sum        if (minPositive + maxNegative >= 0) :Â
            return sum + maxNegativeÂ
        # else remove minPositive no.        else :Â
            return sum - minPositiveÂ
# Driver codearr1 = [ 2, -4, 5, 3 ]arr2 = [ 0, 1, 0, 1 ]Â
n = len(arr1)print(maxSum(arr1, arr2, n))Â
# This code is contributed by divyamohan123 |
C#
// C# program to find the maximum SoP // of two arrays by toggling adjacent bits // in the second arrayusing System;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â class GFG{Â
// Function to return Max Sumstatic int maxSum(int []arr1, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int []arr2, int n){Â Â Â Â // intialParity and finalParity are 0Â Â Â Â // if total no. of 1's is even else 1Â Â Â Â int initialParity = 0, finalParity = 0;Â
    // minPositive and maxNegative will store    // smallest positive and smallest negative    // integer respectively.    int sum = 0,        minPositive = int.MaxValue,        maxNegative = int.MinValue;Â
    for (int i = 0; i < n; i++)    {Â
        // Count of Initial Parity        initialParity += arr2[i];Â
        // if arr1[i] is positive then add 1        // in finalParity to get 1 at arr2[i]        if (arr1[i] >= 0)        {Â
            finalParity += 1;            sum += arr1[i];            minPositive = Math.Min(minPositive,                                       arr1[i]);        }        else        {            maxNegative = Math.Max(maxNegative,                                       arr1[i]);        }    }Â
    // if both parity are odd or even    // then return sum    if (initialParity % 2 == finalParity % 2)    {        return sum;    }Â
    // else add one more 1 or remove 1    else    {Â
        // if minPositive > maxNegative,        // put 1 at maxNegative        // and add it to our sum        if (minPositive + maxNegative >= 0)        {            return sum + maxNegative;        }Â
        // else remove minPositive no.        else        {            return sum - minPositive;        }    }}Â
// Driver codepublic static void Main(String []args){Â Â Â Â int []arr1 = { 2, -4, 5, 3 };Â Â Â Â int []arr2 = { 0, 1, 0, 1 };Â
    int n = arr1.Length;    Console.WriteLine(maxSum(arr1, arr2, n));}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// JavaScript program to find the maximum SoP// of two arrays by toggling adjacent bits// in the second arrayÂ
Â
// Function to return Max Sumfunction maxSum(arr1, arr2, n) {Â Â Â Â // intialParity and finalParity are 0Â Â Â Â // if total no. of 1's is even else 1Â Â Â Â let initialParity = 0, finalParity = 0;Â
    // minPositive and maxNegative will store    // smallest positive and smallest negative    // integer respectively.    let sum = 0,        minPositive = Number.MAX_SAFE_INTEGER,        maxNegative = Number.MIN_SAFE_INTEGER;Â
    for (let i = 0; i < n; i++) {Â
        // Count of Initial Parity        initialParity += arr2[i];Â
        // if arr1[i] is positive then add 1        // in finalParity to get 1 at arr2[i]        if (arr1[i] >= 0) {Â
            finalParity += 1;            sum += arr1[i];            minPositive = Math.min(minPositive,                arr1[i]);        }        else {            maxNegative = Math.max(maxNegative,                arr1[i]);        }    }Â
    // if both parity are odd or even    // then return sum    if (initialParity % 2 == finalParity % 2) {        return sum;    }Â
    // else add one more 1 or remove 1    else {Â
        // if minPositive > maxNegative,        // put 1 at maxNegative        // and add it to our sum        if (minPositive + maxNegative >= 0) {            return sum + maxNegative;        }Â
        // else remove minPositive no.        else {            return sum - minPositive;        }    }}Â
// Driver codeÂ
let arr1 = [2, -4, 5, 3];let arr2 = [0, 1, 0, 1];Â
let n = arr1.length;document.write(maxSum(arr1, arr2, n));Â
// This code is contributed by _saurabh_jaiswalÂ
</script> |
Output:Â
8
Â
Time Complexity:Â , where n is the size of the array.
Auxiliary Space: O(1)
Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



