C++ program to find reduced size of the array after removal operations

Suppose we have an array A with n elements. Consider there is a password with n positive integers. We apply the following operations on the array. The operations is to remove two adjacent elements that are not same as each other, then put their sum at that location. So this operation will reduce the size of array by 1. We have to find the shortest possible length of the array after performing these operations.

So, if the input is like A = [2, 1, 3, 1], then the output will be 1, because if we select (1, 3), the array will be [2, 4, 1], then pick (2, 4) to make the array [6, 1], then select the last two to get [7].

Steps

To solve this, we will follow these steps −

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

Example

Let us see the following implementation to get better understanding −

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

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

Input

{ 2, 1, 3, 1 }

Output

1