Shrink an array by removing triplets that satisfy given constraints

class Most important

{

    // Recursive operate to shrink a given array by eradicating adjoining triplets from it

    public static int shrink(int[] arr, int begin, int finish, int ok)

    {

        // Base case

        if (begin > finish)

            return 0;

        

 

        // Maintain observe of the whole variety of parts within the resultant array

        int end result = 0;

 

        /* Case 1: The primary ingredient, arr[start], doesn’t kind a triplet */

 

        // Skip the primary ingredient, and recur for the subsequent ingredient

        end result = 1 + shrink(arr, begin + 1, finish, ok);    // +1 since `begin` is included

 

 

        /* Case 2: The primary ingredient, arr[start], kinds a triplet with some

                `arr[i]` and `arr[j]` */

 

        // Think about all triplets, and examine if they are often faraway from the array

        for (int i = begin + 1; i < finish; i++)

        {

            for (int j = i + 1; j <= finish; j++)

            

                /* Course of present triplet: (arr[start], arr[i], arr[j]) */

 

                // If the distinction between parts of the present triplet is `ok`

                if (arr[i] == arr[start] + ok && arr[j] == arr[i] + ok)

                

                    // Recursively examine if all parts between `begin` & `i` and

                    // between `i` & `j` will be eliminated

                    if (shrink(arr, begin + 1, i 1, ok) == 0 &&

                            shrink(arr, i + 1, j 1, ok) == 0)

                    

                        // Recur for the subsequent ingredient, and replace the end result

                        int n = shrink(arr, j + 1, finish, ok);

                        if (end result > n)

                            end result = n;

                        

                    

                

            

        }

 

        // Return variety of parts within the resultant array

        return end result;

    }

 

    public static void fundamental(String[] args)

    

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

        int ok = 3;

 

        System.out.println(“The overall variety of parts within the resultant array is “

                + shrink(arr, 0, arr.size 1, ok));

    

}

More Posts