C++ program to find number of distinct values we can get after negating a subarray

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements. We select any subset of given numbers and negate these numbers. We have to find maximum number of different values in the array we can get.

So, if the input is like A = [1, 1, 2, 2], then the output will be 4, because we can negate first and last numbers to make the array [-1, 1, 2, -2] with four different values.

Steps

To solve this, we will follow these steps −

Define one set se
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   x := A[i]
   if x is present in se, then:
      insert -x into se
   Otherwise
      insert x into se
return size of se

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A) {
   set<int> se;
   int n = A.size();
   for (int i = 0; i < n; i++) {
      int x = A[i];
      if (se.count(x))
         se.insert(-x);
      else
         se.insert(x);
   }
   return se.size();
}
int main() {
   vector<int> A = { 1, 1, 2, 2 };
   cout << solve(A) << endl;
}

Input

{ 1, 1, 2, 2 }

Output

4
raja
Updated on 03-Mar-2022 07:33:05

Advertisements