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 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;

int solve(vector A) {
   int n = A.size();
   set a;
   for (int i = 0; i  A = { 2, 1, 3, 1 };
   cout 

Input

{ 2, 1, 3, 1 }

Output

1
Updated on: 2022-03-03T10:13:13+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements