Open In App

Maximum Possible Product in Array after performing given Operations

Last Updated : 01 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array with size N. You are allowed to perform two types of operations on the given array as described below:

  1. Choose some position i and j, such that (i is not equals to j), replace the value of a[j] with a[i]*a[j] and remove the number from the ith cell.
  2. Choose some position i and remove the number from the ith cell (This operation can be performed at-most once and at any point of time, not necessarily in the beginning).

The task is to perform exactly N-1 operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it, print the sequence of operations which leads to this maximum number. 

The output should contain exactly N-1 lines:

  • If the operation is of the first type then print 1 i j.
  • If the operation is of the second type then print 2 i.

Note: The array is considered to have 1-based indexing.

Examples:  

Input : a[] = { 5, -2, 0, 1, -3 }
Output : 2 3
         1 1 2
         1 2 4
         1 4 5
Explanation: 
Step 1: a[3] is removed.
Step 2: a[2] = a[2]*a[1] = -10; a[1] is removed.
Step 3: a[4] = a[4]*a[2] = -10; a[2] is removed.
Step 4: a[5] = a[5]*a[4] = 30; a[4] is removed.
So, the maximum product is 30.

Input : a[] = { 0, 0, 0, 0 }
Output : 1 1 2
         1 2 3
         1 3 4

Approach: There are several cases in the problem. Let the number of zeroes in the array be cntZero and the number of negative elements be cntNeg. Also let maxNeg be the position of the maximum negative element in the array, or -1 if there are no negative elements in the array.

Let the answer part be the product of all the numbers which will be in the answer and the removed part be the product of all the numbers which will be removed by the second type of operation.

The cases are as follows:  

  1. The first case is when cntZero=0 and cntNeg=0. Then the answer part is the product of all the numbers in the array. The removed part is empty.
  2. The second case is when cntNeg is odd. Then the answer part is the product of all the numbers in the array except all zeroes and a[maxNeg]. The removed part is the product of all zeroes and a[maxNeg].
  3. The third case is when cntNeg is even. Then the answer part is the product of all the numbers in the array except all zeroes. The removed part is the product of all zeroes in the array (be careful in case cntNeg=0 and cntZero=n).

Below is the implementation of the above idea:  

C++




// CPP program for maximum possible product
// with given array of numbers
#include <bits/stdc++.h>
using namespace std;
 
// Function that prints operations in each step
void MaximumProduct(int a[], int n)
{
    int cntneg = 0;
    int cntzero = 0;
     
    int used[n] = { 0 };
    int pos = -1;
 
    // count number of zeros and negative numbers
    for (int i = 0; i < n; ++i) {
        if (a[i] == 0) {
            used[i] = 1;
            cntzero++;
        }
         
        if (a[i] < 0) {
            cntneg++;
             
            // To get negative number which
            // is nearest to zero, that is maximum
            // negative number
            if (pos == -1 || abs(a[pos]) > abs(a[i]))
                pos = i;
        }
    }
     
    // if number of negative number are odd then
    // remove negative number at position pos
    if (cntneg % 2 == 1)
        used[pos] = 1;
 
    // initial condition
    if (cntzero == n || (cntzero == n - 1 &&
                                    cntneg == 1)) {
        for (int i = 0; i < n - 1; ++i)
            cout << 1 << " " << i + 1 << " "
                                << i + 2 << endl;
        return;
    }
 
    int lst = -1;
    for (int i = 0; i < n; ++i) {
        if (used[i]) {
            if (lst != -1)
                cout << 1 << " " << lst + 1 << " "
                                << i + 1 << endl;
            lst = i;
        }
    }
     
    // perform second type operation
    if (lst != -1)
        cout << 2 << " " << lst + 1 << endl;
 
    lst = -1;
     
    // for remaining numbers
    for (int i = 0; i < n; ++i) {
        // if it is not removed yet
        if (!used[i]) {
            if (lst != -1)
                cout << 1 << " " << lst + 1 << " "
                                    << i + 1 << endl;
            lst = i;
        }
    }
}
 
// Driver code
int main()
{
    int a[] = { 5, -2, 0, 1, -3 };
 
    int n = sizeof(a) / sizeof(a[0]);
 
    MaximumProduct(a, n);
 
    return 0;
}


C




// C program for maximum possible product
// with given array of numbers
#include <stdio.h>
#include <stdlib.h>
 
// Function that prints operations in each step
void MaximumProduct(int a[], int n)
{
  int cntneg = 0;
  int cntzero = 0;
 
  int used[n];
  //initializing the array as 0
  for (int i = 0; i < n; i++)
  {
    used[i] = 0;
  }
  int pos = -1;
 
  // count number of zeros and negative numbers
  for (int i = 0; i < n; ++i) {
    if (a[i] == 0) {
      used[i] = 1;
      cntzero++;
    }
 
    if (a[i] < 0) {
      cntneg++;
 
      // To get negative number which
      // is nearest to zero, that is maximum
      // negative number
      if (pos == -1 || abs(a[pos]) > abs(a[i]))
        pos = i;
    }
  }
 
  // if number of negative number are odd then
  // remove negative number at position pos
  if (cntneg % 2 == 1)
    used[pos] = 1;
 
  // initial condition
  if (cntzero == n || (cntzero == n - 1 &&
                       cntneg == 1)) {
    for (int i = 0; i < n - 1; ++i)
      printf("%d %d %d\n", 1, i + 1, i + 2);
    return;
  }
 
  int lst = -1;
  for (int i = 0; i < n; ++i) {
    if (used[i]) {
      if (lst != -1)
        printf("%d %d %d\n", 1, lst+1, i+1);
      lst = i;
    }
  }
 
  // perform second type operation
  if (lst != -1)
    printf("%d %d\n", 2, lst + 1);
 
 
  lst = -1;
 
  // for remaining numbers
  for (int i = 0; i < n; ++i) {
    // if it is not removed yet
    if (!used[i]) {
      if (lst != -1)
        printf("%d %d %d\n", 1, lst + 1, i+1);
 
      lst = i;
    }
  }
}
 
// Driver code
int main()
{
  int a[] = { 5, -2, 0, 1, -3 };
  int n = sizeof(a) / sizeof(a[0]);
  MaximumProduct(a, n);
  return 0;
}
 
// This code is contributed by phalashi.


Java




// Java program for maximum possible product
// with given array of numbers
class GFG {
 
// Function that prints operations in each step
static void MaximumProduct(int a[], int n) {
    int cntneg = 0;
    int cntzero = 0;
 
    int used[] = new int[n];
    int pos = -1;
     
    // count number of zeros and negative numbers
    for (int i = 0; i < n; ++i) {
        if (a[i] == 0)
        {
            used[i] = 1;
            cntzero++;
             
        }
         
        if (a[i] < 0) {
            cntneg++;
             
            // To get negative number which
            // is nearest to zero, that is maximum
            // negative number
            if (pos == -1 || Math.abs(a[pos]) > Math.abs(a[i])) {
                pos = i;
                 
            }
             
        }
         
    }
     
    // if number of negative number are odd then
    // remove negative number at position pos
    if (cntneg % 2 == 1) {
        used[pos] = 1;
         
    }
     
    // initial condition
    if (cntzero == n || (cntzero == n - 1 && cntneg == 1))
    {             
        for (int i = 0; i < n - 1; ++i) {
            System.out.println(1 + " " + (i + 1) + " "
                        + (i + 2));
             
        }
        return;
         
    }
     
    int lst = -1;
    for (int i = 0; i < n; ++i) {
        if (used[i] == 1) {
            if (lst != -1) {
                System.out.println(1 + " " + (lst + 1) + " "
                            + (i + 1));
                 
            }
            lst = i;
             
        }
         
    }
     
    // perform second type operations
    if (lst != -1) {
        System.out.println(2 + " " + (lst + 1));
         
    }
    lst = -1;
    // for remaining numbers
    for (int i = 0; i < n; ++i)
    {
        // if it is not removed yet
        if (used[i] != 1)
        {
            if (lst != -1)
            {
                System.out.println(1 + " " + (lst + 1) + " "
                            + (i + 1));
                 
            }
            lst = i;
        }
    }
     
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = {5, -2, 0, 1, -3};
    int n = a.length;
    MaximumProduct(a, n);
     
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 program for maximum possible product
# with given array of numbers
 
# Function that prints operations
# in each step
def MaximumProduct(a, n):
    cntneg = 0
    cntzero = 0
     
    used = [0] * n
    pos = -1
 
    # count number of zeros and
    # negative numbers
    for i in range(n):
        if (a[i] == 0) :
            used[i] = 1
            cntzero += 1
         
        if (a[i] < 0):
            cntneg += 1
             
            # To get negative number which
            # is nearest to zero, that is maximum
            # negative number
            if (pos == -1 or abs(a[pos]) > abs(a[i])):
                pos = i
     
    # if number of negative number are odd then
    # remove negative number at position pos
    if (cntneg % 2 == 1):
        used[pos] = 1
 
    # initial condition
    if (cntzero == n or (cntzero == n - 1 and
                         cntneg == 1)):
        for i in range(n - 1):
            print (1, " ", i + 1, " ", i + 2)
        return
 
    lst = -1
    for i in range(n) :
        if (used[i]) :
            if (lst != -1):
                print (1, " ", lst + 1, " ", i + 1)
            lst = i
     
    # perform second type operation
    if (lst != -1):
        print (2, " ", lst + 1)
 
    lst = -1
     
    # for remaining numbers
    for i in range( n) :
         
        # if it is not removed yet
        if (not used[i]) :
            if (lst != -1):
                print (1, " ", lst + 1, " ", i + 1)
            lst = i
     
# Driver code
if __name__ == "__main__":
    a = [ 5, -2, 0, 1, -3 ]
 
    n = len(a)
 
    MaximumProduct(a, n)
 
# This code is contributed by ita_c


C#




// C# program for maximum possible product
// with given array of numbers
using System;
 
class GFG
{
     
// Function that prints
// operations in each step
static void MaximumProduct(int []a, int n)
{
    int cntneg = 0;
    int cntzero = 0;
 
    int []used = new int[n];
    int pos = -1;
     
    // count number of zeros
    // and negative numbers
    for (int i = 0; i < n; ++i)
    {
        if (a[i] == 0)
        {
            used[i] = 1;
            cntzero++;
             
        }
         
        if (a[i] < 0)
        {
            cntneg++;
             
            // To get negative number which
            // is nearest to zero, that is
            //  maximum negative number
            if (pos == -1 || Math.Abs(a[pos]) >
                                Math.Abs(a[i]))
            {
                pos = i;
                 
            }
             
        }
         
    }
     
    // if number of negative number are odd then
    // remove negative number at position pos
    if (cntneg % 2 == 1)
    {
        used[pos] = 1;
         
    }
     
    // initial condition
    if (cntzero == n || (cntzero == n - 1 &&
                                cntneg == 1))
    {        
        for (int i = 0; i < n - 1; ++i)
        {
            Console.WriteLine(1 + " " + (i + 1) + " "
                        + (i + 2));
        }
        return;
         
    }
     
    int lst = -1;
    for (int i = 0; i < n; ++i)
    {
        if (used[i] == 1)
        {
            if (lst != -1)
            {
                Console.WriteLine(1 + " " + (lst + 1) + " "
                            + (i + 1));
            }
            lst = i;
             
        }
         
    }
     
    // perform second type operations
    if (lst != -1)
    {
        Console.WriteLine(2 + " " + (lst + 1));
         
    }
    lst = -1;
     
    // for remaining numbers
    for (int i = 0; i < n; ++i)
    {
        // if it is not removed yet
        if (used[i] != 1)
        {
            if (lst != -1)
            {
                Console.WriteLine(1 + " " + (lst + 1) + " "
                            + (i + 1));
            }
            lst = i;
        }
    }
     
}
 
    // Driver code
    static public void Main ()
    {
        int []a = {5, -2, 0, 1, -3};
        int n = a.Length;
        MaximumProduct(a, n);
    }
}
 
// This code is contributed by ajit


Javascript




<script>
 
// JavaScript program for maximum possible product
// with given array of numbers
 
// Function that prints operations in each step
function MaximumProduct(a, n)
{
    let cntneg = 0;
    let cntzero = 0;
     
    let used = new Uint8Array(n);
    let pos = -1;
 
    // count number of zeros and negative numbers
    for (let i = 0; i < n; ++i) {
        if (a[i] == 0) {
            used[i] = 1;
            cntzero++;
        }
         
        if (a[i] < 0) {
            cntneg++;
             
            // To get negative number which
            // is nearest to zero, that is maximum
            // negative number
            if (pos == -1 || Math.abs(a[pos]) > Math.abs(a[i]))
                pos = i;
        }
    }
     
    // if number of negative number are odd then
    // remove negative number at position pos
    if (cntneg % 2 == 1)
        used[pos] = 1;
 
    // initial condition
    if (cntzero == n || (cntzero == n - 1 &&
                                    cntneg == 1)) {
        for (let i = 0; i < n - 1; ++i)
            document.write(1 + " " + (i + 1) + " "
                                + (i + 2) + "<br>");
        return;
    }
 
    let lst = -1;
    for (let i = 0; i < n; ++i) {
        if (used[i]) {
            if (lst != -1)
                document.write(1 + " " + (lst + 1) + " "
                                + (i + 1) + "<br>");
            lst = i;
        }
    }
     
    // perform second type operation
    if (lst != -1)
        document.write(2 + " " + (lst + 1) + "<br>");
 
    lst = -1;
     
    // for remaining numbers
    for (let i = 0; i < n; ++i) {
        // if it is not removed yet
        if (!used[i]) {
            if (lst != -1)
                document.write(1 + " " + (lst + 1) + " "
                                    + (i + 1) + "<br>");
            lst = i;
        }
    }
}
 
// Driver code
 
    let a = [ 5, -2, 0, 1, -3 ];
 
    let n = a.length;
 
    MaximumProduct(a, n);
 
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output

2 3
1 1 2
1 2 4
1 4 5

Complexity Analysis:

  • Time Complexity: O(n), where n represents the size of the given array.
  • Auxiliary Space: O(n), where n represents the size of the given array.


Similar Reads

Maximum possible Array sum after performing given operations
Given array arr[] of positive integers, an integer Q, and arrays X[] and Y[] of size Q. For each element in arrays X[] and Y[], we can perform the below operations: For each query from array X[] and Y[], select at most X[i] elements from array arr[] and replace all the selected elements with integer Y[i].After performing Q operations, the task is t
9 min read
Maximum score possible after performing given operations on an Array
Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times: If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. If the operation is even-numbered, the score is decreme
29 min read
Maximise minimum element possible in Array after performing given operations
Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. Find the maximum possible minimum element of the ar
11 min read
Maximum sum possible from given Matrix by performing given operations
Given a matrix arr[][] of dimensions 2 * N, the task is to maximize the sum possible by selecting at most one element from each column such that no two consecutive elements are chosen from the same row. Examples: Input: arr[][] = {{1, 50, 21, 5}, {2, 10, 10, 5}}Output: 67Explanation: Elements arr[1][0]( = 2), arr[0][1]( = 50), arr[0][2]( = 10) and
11 min read
Average value of set bit count in given Binary string after performing all possible choices of K operations
Given a positive integer N and an array arr[] consisting of K integers and consider a binary string(say S) having N set bits, the task is to find the average value of the count of set bits after performing over all possible choices of K operations on the string S such that in the ith operation, any of the arr[i] bits out of N bits can be flipped. E
8 min read
Count of distinct possible strings after performing given operations
Given a numeric string S consisting of only three types of characters 0, 1, and 2 initially and following two operations: The occurrence of two consecutive 1 can be replaced by 3.The occurrence of two consecutive 2 can be replaced by 4.The given task is to find the total number of different strings that can be formed by using the operations.Example
10 min read
Maximum count of equal numbers in an array after performing given operations
Given an array of integers. The task is to find the maximum count of equal numbers in an array after applying the given operation any number of times. In an operation: Choose two elements of the array a[i], a[j] (such that i is not equals to j) and, Increase number a[i] by 1 and decrease number a[j] by 1 i.e., a[i] = a[i] + 1 and a[j] = a[j] - 1. E
5 min read
Maximum sum of all elements of array after performing given operations
Given an array of integers. The task is to find the maximum sum of all the elements of the array after performing the given two operations once each. The operations are: 1. Select some(possibly none) continuous elements from the beginning of the array and multiply by -1. 2. Select some(possibly none) continuous elements from the end of the array an
7 min read
Maximum number of unique values in the array after performing given operations
Given an array arr[] of size N and every element in the array arr[] is in the range [1, N] and the array may contain duplicates. The task is to find the maximum number of unique values that can be obtained such that the value at any index i can either be: Increased by 1.Decreased by 1.Left as it is. Note: The operation can be performed only once wi
12 min read
Maximum count of values of S modulo M lying in a range [L, R] after performing given operations on the array
Given an array arr[] of N integers along with integers M, L, R. Consider a variable S(initially 0). The task is to find the maximum count of values of S % M that lies in the range [L, R] after performing the following operations for each element in the given array: Add arr[i] or arr[i] - 1 to S.Change S to S % M. Examples: Input: arr[] = {17, 11, 1
11 min read