Beautiful Array

  • + 0 comments

    I think they notice that the n k l values are very small, so a bf approach would be good enough to solve the problem, not necessary to find the best solution.

    Below is the bf approach I wrote in java passed all cases in less than 0.2s, max is the max value, target can be the median, you just need to loop through all values between target and max value to find the min cost.

    INCLUDED INCLUDED INCLUDED

    while(max >= target){

            belowSum = 0;
            aboveSum = 0;
            for(int i = 0; i < size; i++){
                if(num[i] < max)
                    belowSum+=(max-num[i]);
                else if(num[i] > max)
                    aboveSum+=(num[i]-max);
            }
            int temp = aboveSum*k + (belowSum-aboveSum)*l;
            if(temp < ans)
                ans = temp;
            max--;
        }