Maximum Possible Product in Array after performing given Operations in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum Possible Product in Array after performing given Operations

For this we will be provided with an array of size N. Our task is to perform N-1 operations (changing a[j] → a[i]*a[j] and remove a[i] value or just remove the value of a[i] (only once)) such that the remaining values are the maximum ones only.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//printing operations
void MaximumProduct(int a[], int n) {
   int cntneg = 0;
   int cntzero = 0;
   int used[n] = { 0 };
   int pos = -1;
   for (int i = 0; i < n; ++i) {
      if (a[i] == 0) {
         used[i] = 1;
         cntzero++;
   }
   if (a[i] < 0) {
      cntneg++;
      if (pos == -1 || abs(a[pos]) > abs(a[i]))
         pos = i;
      }
   }
   if (cntneg % 2 == 1)
      used[pos] = 1;
   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;
      }
   }
   if (lst != -1)
      cout << 2 << " " << lst + 1 << endl;
   lst = -1;
   for (int i = 0; i < n; ++i) {
      if (!used[i]) {
         if (lst != -1)
            cout << 1 << " " << lst + 1 << " " << i + 1 << endl;
         lst = i;
      }
   }
}
int main() {
   int a[] = { 5, -2, 0, 1, -3 };
   int n = sizeof(a) / sizeof(a[0]);
   MaximumProduct(a, n);
   return 0;
}

Output

2 3
1 1 2
1 2 4
1 4 5
raja
Published on 09-Sep-2020 12:34:38
Advertisements