Find minimum possible size of array with given rules for removing elements in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n numbers and an integer value k. Our task is to Find minimum possible size of the array with given rules for removing elements.

Problem Description − we need to minimise the number of elements in the array. By using the follow deletion operation, The number of elements that can be removed at once is 3. The removal is possible if the three elements satisfy the two given conditions,

Cond 1 − Three elements should be adjacent.>

Cond 2 − the difference between two nearby elements is k, i.e. arr[i + 1] = arr[i] + k and arr[i+2] = arr[i+1] + k.

Let’s take an example to understand the problem,

Input

{4, 6, 8, 4, 1, 5 }, k = 2

Output

3

Explanation

One deletion operation is possible, for index 0, 1, 2.

Solution Approach

This problem is a bit tricky to solve as there can be indirect deletion operations possible that can be seen after one deletion operation is done. For example one we delete elements at 5, 6, 7. After this deletion, the new array might have elements 3, 4, 5 that now satisfy the condition for deletion. Such types of problems which have overlapping subproblems can be solved using a dynamic programming approach. For this, we will maintain a DP[] matrix to store results of the subproblems to access them later when required, this is called memorisation.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
int DP[MAX][MAX];
int calcMinSize(int arr[], int start, int end, int k){
   if (DP[start][end] != -1)
      return DP[start][end];
   if ( (end-start + 1) < 3)
      return end-start +1;
   int minSize = 1 + calcMinSize(arr, start+1, end, k);
   for (int i = start+1; i<=end-1; i++){
      for (int j = i+1; j <= end; j++ ){
         if (arr[i] == (arr[start] + k) && arr[j] == (arr[start] +
            2*k) && calcMinSize(arr, start+1, i-1, k) == 0 && calcMinSize(arr, i+1, j- 1, k) == 0) {
            minSize = min(minSize, calcMinSize(arr, j+1, end, k));
         }
      }
   }
   return (DP[start][end] = minSize);
}
int main() {
   int arr[] = {4, 6, 8, 4, 1, 5 };
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 2;
   memset(DP, -1, sizeof(DP));
   cout<<"The minimum possible size of the array after removal is "<<calcMinSize(arr, 0, n-1, k);
   return 0;
}

Output

The minimum possible size of the array after removal is 3
raja
Published on 12-Mar-2021 07:03:35
Advertisements