Date:

Share:

Shrink an array by removing triplets that satisfy given constraints – Techie Delight

Related Articles

status main

{

// A recursive function to shrink a given array by removing adjacent triplets from it

public static int shrivel(int[] arr, int start, int end, int K)

{

// Basic case

If (start > end)

Return 0;

// Keep track of the total number of elements in the created array

int outcome = 0;

/ * Case 1: The first element, arr[start], Does not form a trio * /

// Skip the first element, and repeat the next element

outcome = 1 + shrivel(arr, start + 1, end, K); // 1+ since ‘Start’ is included

/ * Case 2: The first element, arr[start], Creates a trio with a few

`Ar[i]`And`r[j]`* /

// Consider all the triplets, and see if they can be removed from the array

To (int I am = start + 1; I am < end; I am++)

{

To (int י = I am + 1; י <= end; י++)

/ * Triple Current Processing: (arr[start], arr[i], arr[j]) * /

// If the difference between the current triplet components is `k`

If (arr[i] == arr[start] + K && arr[j] == arr[i] + K)

// Recursively check if all the components between `start` and` i` and

// Between `i` and` j` can be removed

If (shrivel(arr, start + 1, I am 1, K) == 0 &&

shrivel(arr, I am + 1, י 1, K) == 0)

// Repeat the next element, and update the result

int N = shrivel(arr, י + 1, end, K);

If (outcome > N)

outcome = N;

}

// Return some elements in the created array

Return outcome;

}

public static void main(wire[] args)

int[] arr = 1, 2, 5, 8, 2, 5 ;

int K = 3;

editorial board.outside.println(“The total number of elements in the created array is”

+ shrivel(arr, 0, arr.Length 1, K));

}

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles