Help in this question

You are given an array a of integer of size N.

Now, select any two adjacent indices,
ifa[i] == a[i+1], then remove both a[i] && a[i+1] and put add a[i]+1 in the same array

Print the maximum of the number left.

For Example
if a = [4, 3,3, 4, 4,4]
4,4,4,4 first step
5,4,4 second step
5,5 third step
6 fourth step
6 is the answer
Help me in coding this
> if a = [4, 3,3, 4, 4,4]
> 4,4,4,4 first step

Why isn't it [4,4,4,4,4] after the first step?
You replace 3,3 with 4.

After a replacement, do you start at the beginning of the array again, or carry on from the new a[i] just calculated?



For Example
if a = [4, 3,3, 4, 4,4]

I suspect you meant:
if a = [4, 3,3, 4, 4 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <algorithm>
using namespace std;

//==========================================================

void check( int A[], int finish )
{
   for ( int i = 0; i <= finish; i++ ) cout << A[i] << " ";
   cout << '\n';
}

//==========================================================

void fixit( int A[], int start, int &finish )
{
   if ( start >= finish ) return;

   if ( A[start] == A[start+1] )
   {
      A[start]++;
      for ( int i = start + 1; i < finish; i++ ) A[i] = A[i+1];
      finish--;
         check( A, finish );
      fixit( A, max( start - 1, 0 ), finish );
   }
   else
   {
      fixit( A, start + 1, finish );
   }
}

//==========================================================

int main()
{
   int A[] = { 4, 3, 3, 4, 4 };
   int finish = sizeof A / sizeof A[0] - 1;
      check( A, finish );
   fixit( A, 0, finish );
   cout << "Answer: " << *max_element( A, A + finish + 1 );
}


4 3 3 4 4 
4 4 4 4 
5 4 4 
5 5 
6 
Answer: 6
Registered users can post here. Sign in or register to post.