Sort an array after applying the given equation

 

Given an integer array arr[] sorted in ascending order, along with three integers: A, B, and C. The task is to transform each element x in the array using the quadratic function A*(x^2) + B*x + C. After applying this transformation to every element, return the modified array in sorted order.

 

Input: arr[] = [-4, -2, 0, 2, 4], A = 1, B = 3, C = 5
Output: [3, 5, 9, 15, 33]
Explanation: After applying f(x) = 1*x2+ 3*x + 5 to each x, we get [9, 3, 5, 15, 33]. After sorting this array, the array becomes [3, 5, 9, 15, 33].

Input: arr[] = [-3, -1, 2, 4], A = -1, B = 0, C = 0
Output: [-16, -9, -4, -1]
Explanation: After applying f(x) = -1*x2 to each x, we get [-9, -1, -4, -16 ]. After sorting this array, the array becomes [-16, -9, -4, -1].

Input: arr[] = [-1, 0, 1, 2, 3, 4], A = -1, B = 2, C = -1
Output: [-9, -4, -4, -1, -1, 0]

class gfg{

    public List<Integer> sortEquation(int[] arr, int A, int B,int C){

                int left = 0;

                 int n = arr.length;

                int index = A>=0 ? n-1 : 0;

                int[] newArray = new int[n];

                for(int i=0;i<n;i++){

                    left = evaluate(arr[i ],A,B,C);

                    right = evaluate(arr[n-1-i),A,B,C);

                    if(A>=0){

                            if( left >= right ){

                                    newArray[index--] = left;

                                    left++; 

                            }else{                                         

                                     newArray[index--] = right;

                                        right--;

                        }else{                                         

                            if(left < right){

                                        newArray[index++] = left;

                                                    left++;

                            }else{

                                        newArray[index++] = right;

                                                        right--;

                            }

                    }

        }

   private int evaluate(int x,int a,int b,int c) {

            return a*x*x +b*x+c;

    }

 

Comments

Popular Posts