![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to find number of distinct values we can get after negating a subarray
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
Advertisements