Given an integer array, shrink it by removing adjacent triplets that satisfy the given constraints and return the total number of elements in the resultant array.

A triplet (x, y, z) can only be removed if, for a given number k, the second element y of the triplet is precise k more than the first element x. The third element, z, is precise k more than the second element y. The total number of elements in the final array should be as few as possible.

 
For example,

Input:  A[] = [1, 2, 3, 5, 7, 8], k = 2
 
Output: 3
 
The adjacent triplet (3, 5, 7) can be removed from the array. The resultant array is [1, 2, 8] cannot be reduced further.
 
 
Input:  A[] = [-1, 0, 1, 2, 3, 4], k = 1
 
Output: 0
 
The result is 0 since we can remove all elements from the array. First, the adjacent triplet (2, 3, 4) is removed. The array is now reduced to [-1, 0, 1], which forms another valid triplet and can be removed from the array.
 
Note that if the adjacent triplet (1, 2, 3) is removed from the array first, we cannot reduce the resultant array [-1, 0, 4] further.

Practice this problem

For each element x in the array, there are two alternatives:

  1. It does not form a triplet with any other elements in the array.
  2. It forms a triplet with elements y and z in the array. To form a triplet, the difference between y-x and z-y should be both equal to k. Also, if the triplet (x, y, z) is not consecutive, then to remove it from the array, all elements between x & y and between y & x should form valid triplets and removed first.

The idea is to recursively check for all triplets and consider the combination that results in fewer elements in the final array. The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The total number of elements in the resultant array is 0

Java


Download  Run Code

Output:

The total number of elements in the resultant array is 0

Python


Download  Run Code

Output:

The total number of elements in the resultant array is 0

The time complexity of the above solution is exponential as several subproblems are recalculated over and over again, i.e., it exhibits overlapping subproblems. The repeated subproblems can be easily seen by drawing a recursion tree for larger values of n. The problem also has an optimal substructure since it can be recursively broken down into smaller subproblems.

 
The problems having an optimal substructure and overlapping subproblems can be solved using dynamic programming. The dynamic programming solution is left as an exercise to readers (Hint – save solutions to the subproblems in a hash table).